Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 奇怪!静态常量unsigned不是类模板中的常量表达式吗?_C++_Templates_Template Specialization - Fatal编程技术网

C++ 奇怪!静态常量unsigned不是类模板中的常量表达式吗?

C++ 奇怪!静态常量unsigned不是类模板中的常量表达式吗?,c++,templates,template-specialization,C++,Templates,Template Specialization,代码在这里。编译器是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

代码在这里。编译器是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//普通类没问题。但模板有问题。
甲级
{
const static unsigned N=2;//不正常
//枚举{N=2};//这没关系
模板void Fun(){}
模板void Fun(){}//错误C2975非常量表达式
};

为什么??谢谢。

编译器可能给出了错误的错误消息,但代码格式不正确,因为
模板
类{}
范围内无效。它声明了一个显式专门化,它只能出现在命名空间范围中

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

尝试使用重载和SFINAE。函数模板专门化通常是个坏主意

template<unsigned i> typename std::enable_if< i != N >::type Fun() {}
template<unsigned i> typename std::enable_if< i == N >::type Fun() {}
template typename std::如果::键入Fun(){}
模板typename std::enable_if::type Fun(){}

摆脱
N
并使用
Fun
,您应该得到相同的错误,至少在GCC 4.8.1上是这样(我假设VS会有错误,但您没有发布错误)。这对你问题的标题确实有影响。@chris我更正了我的问题。谢谢。对不起,我没听懂。当你说无效时,是不是意味着不可编译?你的爱好是什么?调用Fun()时,会出现编译错误吗?谢谢。@user1899020编译器一看到
类{}
中的
模板
就应该放弃。是的,无效的方法无法编译。如果编译器从未编译过
Fun
的声明,那么如果它继续执行
Fun
,也将导致另一个错误。如果您使用我建议的声明,并且它们确实在您的程序中起作用,那么
Fun
Fun
将根据您的需要分派到不同的函数。