Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How-to specialize template method in subclass(c++)?

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?

like image 545
Dmitriy Avatar asked Nov 14 '10 09:11

Dmitriy


1 Answers

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.

like image 176
vitaut Avatar answered Sep 21 '22 21:09

vitaut