user3600124 user3600124 - 12 days ago 6
C++ Question

Inheritance of a template class

template <typename T>
class store // Very basic class, capable of accepting any data-type and does nothing too much
{
public:
store(T value) : value(value) {}
private:
T value;
}

template <>
class store<int> // Inherits all the basic functionality that the above class has and it also has additional methods
: public store<int> // PROBLEM OVER HERE. How do I refer to the above class?
{
public:
store(int value) : store<int>(value) /* PROBLEM OVER HERE. Should refer to the constructor of the above class */ {}
void my_additional_int_method();
}


Here I have problem with the inheritance. I do not want to change the name of the base class because the base class serves for the same purpose as all the derived classes (the only difference - derived classes have few extra methods)

Answer

You can maybe do something like this:

template <typename T>
class store_impl
{
  public:
    store_impl(T value) : value(value) {}
  private:
    T value;
}

// default class accepting any type
// provides the default methods
template <typename T>
class store: public store_impl<T>
{
public:
    store(T value) : store_impl(value) {}
}

// specialization for int with extra methods
template <>
class store<int>: public store_impl<int>
{
  public:
    store(int value) : store_impl<int>(value)
    {}
    void my_additional_int_method();
}
Comments