c++ - decltype 的另一个问题

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

最佳答案

首先要注意的是,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 检查类型是否相同。它们都是 charvalues 1 和 'a'。

    return 0;
}

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

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

相关文章:

C++ 实现我自己的 static_assert

C++ 我有一个类数组,我想访问它的元素

c++ - 在 decltype 中使用 this 指针

c++ - 如何在 constexpr if-else 链中导致静态错误?

c++ - 如果可能的话静态断言,否则动态断言?

c++ - `decltype` 是给我一个对象的静态类型,还是它的运行时类型?

c++ - 如何在类中实现可选属性

c++ - 堆栈跟踪分析工具

c++ - 使用 shared_ptr 在中断时结束多线程循环

c++ - 什么是 decltype(0 + 0)?