我正在尝试在其子类中专门化非模板类的模板方法:
// .h 文件
class MyWriter {
public:
template<typename T>
void test(const T & val) {
std::cout << val << "\n";
}
};
// .cpp 文件
class MyType {
public:
MyType(int aa, double dd) : a(aa), d(dd) {}
int a;
double d;
};
class MyWriterExt : public MyWriter {
public:
template<> void test(const MyType &val) {
test(val.a);
test(val.d);
}
};
int main() {
MyWriterExt w;
w.test(10);
w.test(9.999);
w.test(MyType(15, 0.25));
return 0;
}
但我收到一个错误:
Error 1 **error C2912**: explicit specialization;
'void MyWriterExt::test(const MyType &)' is not a specialization of a function
template \testtemplate.cpp 30
如何扩展 MyWriter 类以支持用户定义的类?