Alex Rivera | Logout

Overriding a function only for certain types in template

Asked 2012-06-02T15:11:20.980
8

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?

Edit
Report

1 Answer

8

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() { /* ... */ }
answered 2012-06-02T15:29:58.180

Your Answer