可以在模板定义之外专门化一些类成员函数:
template<class A>
struct B {
void f();
};
template<>
void B<int>::f() { ... }
template<>
void B<bool>::f() { ... }
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我甚至可以省略f一般类型的函数定义A.
但是如何把这个专业化放在课堂上呢?像这样:
template<class A>
struct B {
void f();
void f<int>() { ... }
void f<bool>() { ... }
};
Run Code Online (Sandbox Code Playgroud)
在这种情况下我应该使用什么语法?
编辑:目前使用最少代码行的解决方案是添加假模板函数f定义并从原始函数显式调用它f:
template<class A>
struct B {
void f() { f<A>(); }
template<class B>
void f();
template<>
void f<int>() { ... }
template<>
void f<bool>() { ... }
};
Run Code Online (Sandbox Code Playgroud)
你应该把专业化放在struct:
template<>
struct B<int> {
void f() { ... }
};
template<>
struct B<bool> {
void f() { ... }
};
Run Code Online (Sandbox Code Playgroud)
无法在定义模板化版本的同一个类中专门化成员函数.要么必须在类外部明确地专门化成员函数,要么使用成员函数专门化整个类.