Different implementation of a class template method for a particular type of class template

I have a template class with a method for which I need another implementation for a specific type of template. How to do it?

+4
source share
3 answers

You can specialize a method for this type. For instance.

template<typename T> struct TemplatedClass { std::string methodA () {return "T methodA";} std::string methodB () {return "T methodB";} std::string methodC () {return "T methodC";} }; // Specialise methodA for int. template<> std::string TemplatedClass<int>::methodA () { return "int methodA"; } 
+3
source

You will need to create a partial (or full) specialization for this particular type.

+4
source

Timo answer allows you to specialize the class as a whole, which means that the compiler will not automatically copy member functions from the base type to the specialized type.

If you want to specialize a particular method in a class without re-creating everything else, this is a little more complicated. You can do this by passing a template with a zero-size template as an argument, for example:

 template<typename T> struct TypeHolder { }; template<typename T> class TemplateBase { public: void methodInterface() { methodImplementation(TypeHolder<T>); } void anotherMethod() { // implementation for a function that does not // need to be specialized } private: void methodImplementation(TypeHolder<int>) { // implementation for int type } void methodImplementation(TypeHolder<float>) { // implementation for float type } }; 

The compiler embeds the corresponding methodImplementation in the methodInterface , and also removes the structure with a zero size, so it will be exactly the same as if you did specialization only for the member function.

+2
source

All Articles