我看到与我不明白的模板(编译器是Visual Studio 2012)相关的错误.这里的代码,归结为必需品:
// Templated class - generic
template <typename T>
class Test
{
public:
void WorksFine() {} // Comiples and works as expected at runtime
void Problem();
};
// Templated class - expicit specialization for T = int.
template <>
class Test<int>
{
public:
void WorksFine() {} // Comiples and works as expected at runtime
void Problem();
};
// The deFinition below compiles and works fine at runtime.
template<typename T> void Test<T>::Problem() {}
// The deFinition below gives error C2910.
template<> void Test<int>::Problem() {printf("In Test::Problem(int instantiation)\n");}
对于WorksFine方法,函数定义在显式专用的类定义内,一切都很好.但是对于Problem方法,当我定义了明确专门的类定义之外的方法时,我得到错误C2910
为什么是这样?错误C2910表示问题是Test :: Problem()已经被定义.但是它没有在类内定义…没有函数定义只有一个声明.
根据您选择放置功能定义的位置,可以做些不好的事情似乎很跛足,我一直认为更多是风格/语法决定,而不是功能/语义决定.我错过了什么吗?
解决方法
您不需要模板<>.只写:
void Test<int>::Problem() {printf("In Test::Problem(int instantiation)\n");}
模板<>需要在成员专用化上使用语法来明确地实例化一个成员;定义已经存在的专业化的成员时,省略它.
template<typename T> struct X { static int i; };
template<> int X<int>::i = 0; // member instantiation,uses template<>
template<typename T> struct Y { static int i; };
template<> struct Y<int> { static int i; } // template specialization
int Y<int>::i = 0; // no template<>