decltype的另一个问题

时间:2011-02-22 07:17:56

标签: c++ decltype static-assert

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条评论。

3 个答案:

答案 0 :(得分:4)

首先要注意的是,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;
}

您似乎尝试的是创建一个模板,使第二个和第三个参数的类型基于您传入其中的值的任何已解析类型。这是不可能做到的。

答案 1 :(得分:3)

static_assert确实编译,因为模板参数的低位和高位的decltype是char。查看模板定义和实例化。 IntT&lt; - char

要默认初始化您的成员,您可以写下:

X():a(),b()
{

答案 2 :(得分:1)

X():a(decltype(a)()),b(decltype(b)())//WHY THIS DOES NOT COMPILE?
海湾合作委员会汇编得很好。请参阅:http://www.ideone.com/DG7rt

看起来它是MSVC ++ 10编译器错误!