可以在模板定义之外特化一些类成员函数:
template<class A>
struct B {
void f();
};
template<>
void B<int>::f() { ... }
template<>
void B<bool>::f() { ... }
在这种情况下,我什至可以省略通用类型 A
的函数 f
的定义。
但是如何将这个特化放在类中呢?像这样:
template<class A>
struct B {
void f();
void f<int>() { ... }
void f<bool>() { ... }
};
在这种情况下我应该使用什么语法?
编辑:
目前,代码行最少的解决方案是添加一个伪造的模板函数 f
定义,并从原始函数 f
中显式调用它:
template<class A>
struct B {
void f() { f<A>(); }
template<class B>
void f();
template<>
void f<int>() { ... }
template<>
void f<bool>() { ... }
};
最佳答案
你应该把特化放在struct
上:
template<>
struct B<int> {
void f() { ... }
};
template<>
struct B<bool> {
void f() { ... }
};
无法在定义模板版本的同一个类中特化成员函数。您必须在类外部显式特化成员函数,或者特化整个类,其中包含成员函数。
关于c++ - 专门化模板定义中的模板成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10233734/