这是我的代码:
template<typename T1, typename T2> class MyClass
{
public:
template<int num> static int DoSomething();
};
template<typename T1, typename T2> template<int num> int MyClass<T1, T2>::DoSomething()
{
cout << "This is the common method" << endl;
cout << "sizeof(T1) = " << sizeof(T1) << endl;
cout << "sizeof(T2) = " << sizeof(T2) << endl;
return num;
}
效果很好。但是当我尝试添加这个时
template<typename T1, typename T2> template<> int MyClass<T1, T2>::DoSomething<0>()
{
cout << "This is ZERO!!!" << endl;
cout << "sizeof(T1) = " << sizeof(T1) << endl;
cout << "sizeof(T2) = " << sizeof(T2) << endl;
return num;
}
我收到编译器错误: «>» 标记前无效的显式特化 «int MyClass::DoSomething()» 的模板 ID «DoSomething<0>» 不匹配任何模板声明
我使用 g++ 4.6.1 我该怎么办?
最佳答案
不幸的是,如果不特化外部模板,就无法特化作为类模板成员的模板:
C++11 14.7.3/16: In an explicit specialization declaration for a member of a class template or a member template that appears in namespace scope, the member template and some of its enclosing class templates may remain unspecialized, except that the declaration shall not explicitly specialize a class member template if its enclosing class templates are not explicitly specialized as well.
我认为您最好的选择是将额外参数添加到 MyClass
,然后对其进行部分特化。
关于c++ - 模板类特化的模板方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9276389/