gpt4 book ai didi

c++ - 奇怪的! static const unsigned 不是类模板中的常量表达式?

转载 作者:行者123 更新时间:2023-11-30 04:16:42 24 4
gpt4 key购买 nike

代码在这里。编译器是 VC++ 2012。

template<class T> // Normal class is okay. But template has the problem.
class A
{
const static unsigned N = 2; // not okay

// enum {N = 2}; // this is okay

template<unsigned i> void Fun() {}

template<> void Fun<N>() {} // error C2975 not constant expression
};

为什么?谢谢。

最佳答案

编译器可能会给出错误的错误消息,但代码格式不正确,因为 template<>class {} 中无效范围。这声明了一个显式特化,它只能出现在命名空间范围内。

不幸的是,您不能特化类模板成员函数模板,除非是在显式类模板特化下(它不再是类模板)。

尝试改用重载和 SFINAE。函数模板特化通常不是一个好主意。

template<unsigned i> typename std::enable_if< i != N >::type Fun() {}
template<unsigned i> typename std::enable_if< i == N >::type Fun() {}

关于c++ - 奇怪的! static const unsigned 不是类模板中的常量表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17607760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com