I'm trying to specialize a template method of non-template class in its subclass:
// .h file
class MyWriter {
public:
template<typename T>
void test(const T & val) {
std::cout << val << "\n";
}
};
// .cpp file
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;
}
But I receive an error:
Error 1 **error C2912**: explicit specialization;
'void MyWriterExt::test(const MyType &)' is not a specialization of a function
template \testtemplate.cpp 30
How do I extend MyWriter class to support user defined classes?
Specialization should be done for the same class not for a subclass and also outside of the class body:
class MyWriter {
public:
template<typename T>
void test(const T & val) {
std::cout << val << "\n";
}
};
template<>
void MyWriter::test<MyType>(const MyType & val) {
test(val.a);
test(val.d);
}
You don't need a subclass to specialize the original member function template.
Also consider overloading instead of specialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With