C++ VC++;错误:数组实例化的大小来自模板化静态常量
以下代码在gcc上工作,但在VS2012上失败C++ VC++;错误:数组实例化的大小来自模板化静态常量,c++,templates,visual-studio-2012,static,constants,C++,Templates,Visual Studio 2012,Static,Constants,以下代码在gcc上工作,但在VS2012上失败 class test_base{}; template<class DERIVED > class test_CRTP : public test_base { public: const static int n_size; }; //DEFAULT INITIALIZATION temp
class test_base{};
template<class DERIVED >
class test_CRTP : public test_base
{
public:
const static int n_size;
};
//DEFAULT INITIALIZATION
template< class DERIVED >
const int test_CRTP<DERIVED>::n_size = 3;
//TEMPLATE SPECIALIZATION
class test_spec : public test_CRTP<test_spec>{};
template<class test_T>
class MyClass{
public:
void my_method(){
int my_array[test_T::n_size]; //<-VS doesn't like this
}
};
int main()
{
MyClass<test_spec> oClass;
oClass.my_method();
return 0;
}
叮当声和gcc接受了这一点
MSVC对常量static
的类外初始化不满意,将其移动到类内允许MSVC编译它。此问题出现在编译器()的v19.00.23720.0中
模板
类测试CRTP:公共测试库{
公众:
const static int n_size=3;
//^^^^^将其移动到类中。
};
你可以在@Niall上试试,谢谢你的链接,看来我运气不好。因此无法重写静态常量成员变量:(
Compiled with /EHsc /nologo /W4 /c
main.cpp
main.cpp(26): error C2131: expression did not evaluate to a constant
main.cpp(26): note: failure was caused by non-constant arguments or reference to a non-constant symbol
main.cpp(26): note: see usage of 'n_size'
main.cpp(25): note: while compiling class template member function 'void MyClass<test_spec>::my_method(void)'
main.cpp(33): note: see reference to function template instantiation 'void MyClass<test_spec>::my_method(void)' being compiled
main.cpp(32): note: see reference to class template instantiation 'MyClass<test_spec>' being compiled
template <class DERIVED>
class test_CRTP : public test_base {
public:
const static int n_size = 3;
// ^^^^^ moved it into the class.
};