template<class IntT, IntT low = IntT(), IntT high = IntT()>
struct X
{
    static_assert(std::is_same<decltype(low),decltype(high)>::value,"Different types not allowed");//this should give error if types are different
    decltype(low) a;
    decltype(high) b;
    X():a(decltype(a)()),b(decltype(b)())//WHY THIS DOES NOT COMPILE?
    {
        cout << typeid(a).name() << '\n';
        cout << typeid(b).name() << '\n';
    }
};

int _tmain(int argc, _TCHAR* argv[])
{


    X<char,1,'a'> x;//this according to static_assert shouldn't compile but it does

    return 0;
}


使用VS2010。
请在上面的代码中查看3条评论。

最佳答案

首先要注意的是,VS2010已过时并在发布之日就被打破了。 decltype关键字特别有问题,仅适用于最基本的用法。实际上,它得到了很多基本问题,这是完全错误的。

接下来的代码...

template<class IntT, IntT low = IntT(), IntT high = IntT()>
struct X
{
    static_assert(std::is_same<decltype(low),decltype(high)>::value,"Different types not allowed");//this should give error if types are different


但是他们永远不会。

    decltype(low) a;
    decltype(high) b;


您在这里不需要decltype。类型是IntT。

    X():a(decltype(a)()),b(decltype(b)())//WHY THIS DOES NOT COMPILE?


由于VS2010已损坏,通常不允许您使用decltype表达式,就好像它是类型一样。事先使用typedef可能会更好。

幸运的是,您不需要它,因为您可以使用默认构造函数而不是副本。

int _tmain(int argc, _TCHAR* argv[])
{


    X<char,1,'a'> x;//this according to static_assert shouldn't compile but it does


否。static_assert检查类型是否相同。它们均为char,其值为1和'a'。

    return 0;
}


您似乎正在尝试创建一个模板,以使第二个和第三个参数的类型基于您传递给它的值的任何解析类型。无法做到这一点。

关于c++ - decltype的另一个问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5075192/

10-10 22:16
查看更多