The are a number of ways you could do this, if you want your Derived class to use the Base class naturally you could try using a template of templates.
Suppose you have the same Base Class, then derived would have to look like this:
template< class T, template<typename> class Base >
struct Derived : Base<T>
{
typename Base<T>::type field;
int f()
{
return n;
}
int f(int x)
{
return Base<T>::f(x);
}
};
But to instantiate the Derived class you would need to specify the Base class as well.
Like this
Derived<int, Base> object;
Now let's say you don't want that, you just want to instantiate Derived objects from the SAME base class, then you must specialize the derived template.
template< class T, template<typename> class Base = Base >
struct Derived : Base<T>
{
Base<T>::type field;
int f()
{
return n;
}
int f(int x)
{
return Base<T>::f(x);
}
};
This way you can now create Derived<int>
or Derived<string>
LIKE THIS
int main()
{
Derived<int> bs1;
bs1.field = 200;
std::cout << bs1.f() << std::endl;
std::cout << bs1.f(50)<< std::endl;
std::cout << bs1.field<< std::endl;
Derived<std::string> bs2;
bs2.field = "example";
std::cout << bs2.f() << std::endl;
std::cout << bs2.f(50)<< std::endl;
std::cout << bs2.field<< std::endl;
return 0;
}
When you should do this?
When you intend to be switching the base class for some reason, could be for Test Cases. Changing the base class could also change the context.
You could also create a template typedef which would allow you to bring the base property to your own Derived class. This is a good approach.