Overriding a function only for certain types in template

c++, overriding, templates

Solution

Member functions of class templates are in fact function templates, so you can specialize them:

template <typename T> class Foo
{
    void Function();
};

template <typename T> void Foo::Function() { /* ... */ }

template <> void Foo<int>::Function() { /* ... */ }

Problem

I have a base class with a virtual function: ``` class Base { public: virtual void Function(); }; void Base::Function() { cout << "default version" << endl; } ``` and a derived template class: ``` template <class T> class Derived : public Base { public: virtual void Function(); }; ``` Is there a way to make `Function()` be taken from the base class for all types, except some chosen ones? So what I want is to be able to define an overriden `Function()` for, say, `int` and `long`: ``` void Derived<int>::Function() { cout << "overriden version 1" << endl; } void Derived<long>::Function() { cout << "overriden version 2" << endl; } ``` and to have the default version of `Function()` for all other types, without explicit definition of `Function()` for them, so the output of ``` int main () { Derived<int> derivedInt; derivedInt.Function(); Derived<long> derivedLong; derivedLong.Function(); Derived<double> derivedDouble; derivedDouble.Function(); } ``` would be ``` overriden version 1 overriden version 2 default version ``` Is it possible?

Original source