Search code examples
c++parametersparent-childextending-classes

In C++ can you extend a parameterized base class with different parameter value in the child class?


In all the languages that I understand this is not possible but someone was telling me it was possible in C++ but I have a hard time believing it. Essentially when you parameterize a class you are creating a unique class in the compilation stage aren't you?

Let me know if I am not being clear with my question.

Here is my attempt at explaning what I am trying to do ( pay attention to class L ):

//; g++ ModifingBaseClassParameter.cpp -o ModifingBaseClassParameter;ModifingBaseClassParameter

#include <iostream>

using namespace std;

template<typename T>
class Base
{
    public:
        Base() {}
        Base(T& t) : m_t(t) {}
        T& getMem() {return m_t;}
    private:
        T m_t;
};

template<typename T>
class F: Base<T>
{};

template<typename T>
class L: F<long>
{};

int main()
{
     Base<int> i;
     F<float> f;
     L<long> l;

     cout<<i.getMem()<<endl;
//     cout<<f.getMem()<<endl; // why doesn't this work
//     cout<<l.getMem()<<endl; // why doesn't this work
}

So as you can see (hopefully my syntax makes sense) class L is trying to redefine its parent's float parameter to be a long. It certainly doesn't seem like this is legal but I will differ to the experts.


Solution

  • If you mean to ask whether you can do this in c++ :

    template <> 
    class ParamClass<Type1> : public ParamClass<Type2> 
    {
    };
    

    then yes, it is possible.

    It is very often used, for example to define template lists or inherit traits from another type.