如果我有一个类A
template <typename T>
class A { public: void print() const; };
我可以为我所做的特定模板值编写特定版本的方法print
template<> void A<bool>::print() const { printf("A w/ type bool\n"); }
template<> void A<int>::print() const { printf("A w/ type int\n"); }
调用 print 方法只会调用良好实现的代码(编译器告诉我是否没有特定模板的实现。
现在,如果我的类 B
的模板中有多种类型
template <typename T1, typename T2>
class B { public: void print() const; };
如果我尝试像以前一样做,比如说T2
template<typename T1> void B<T1,bool>::print() const { printf("B w/ type bool\n"); }
我收到编译器错误:
error: invalid use of incomplete type 'class B<T1,bool>'
error: declaration of 'class B<T1, bool>'
我做错了什么?
编辑
我现实生活中的 B
类包含其他我不想指定的方法(它们在一般情况下有效)
贴上部分指定的类会使这些泛型方法本身不可用
最佳答案
您不能部分特化函数/方法。
但是你可以部分特化整个类:
template <typename T1, typename T2> class B;
template<typename T1> class B<T1, bool>
{
public:
void print() const { printf("B w/ type bool\n"); }
};
关于c++ - 模板特定方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27408319/