我看到一个与模板有关的错误(编译器是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");}
Run Code Online (Sandbox Code Playgroud)
对于WorksFine方法,函数定义在显式专用的类定义中,一切都很好.但对于Problem方法,当我在显式专用类定义之外定义方法时,我得到错误C2910
为什么是这样?错误C2910表示问题是已定义Test :: Problem().但它没有在类中定义...没有函数定义只有声明.
根据您选择放置函数定义的位置,能够执行某些操作似乎相当蹩脚,我总是更多地考虑样式/语法,而不是功能/语义决策.我错过了什么吗?
你不需要template<>.写吧:
void Test<int>::Problem() {printf("In Test::Problem(int instantiation)\n");}
Run Code Online (Sandbox Code Playgroud)
在template<>上一个成员专门的语法要求,其中明确实例化一个成员自身 ; 定义现有专业化的成员时,将省略它.
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<>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1303 次 |
| 最近记录: |