tags:

views:

155

answers:

3

I have a templated class with a method for which I need a different implementation for a specific template type. How do i get it done?

+4  A: 

You'll have to create a partial (or full) specialization for this particular type.

Timo Geusch
You’ve got to specialize the whole type though, you cannot just partially specialize member functions. This is implicit in the answer but it could be misunderstood.
Konrad Rudolph
You can get around this limitation by using a base class to provide the default implementation (and making the constructors / destructors of this base class protected to avoid using it).
Matthieu M.
+1  A: 

You can specialise the method for that type. E.g.

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";
}
jon hanson
+2  A: 

Timo's answer only allows you to specialize the class as a whole, meaning that the compiler won't automatically copy the member functions from the base type to the specialized type.

If you want to specialize a particular method in the class without re-creating everything else, it's a little more complicated. You can do it by passing a size-zero templated struct as an argument, like this:

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 will inline the appropriate methodImplementation into methodInterface, as well as elide the size-zero struct, so it will be just as if you had done a specialization on the member function only.

int3