knowledge
knowledge

Reputation: 1025

C++ Template Inheritance. Subclass should replace a type in a base class with a fixed type

how can I use a template base class in such a manner that the subclass make a template type "fix".

For example I have a template base class:

template <class A, int size> class BaseClass{
    private:
        A *elem;
    public:
        A()
        {
            elem = new A[size];
        }
};

I can do

BaseClass<int, 5> mybase;

Now I want to make a subclass which has only the parameter size and the type should be int, i.e. the subclass should replace type A in the base class with a fixed type (e.g. int)

Something like this:

SubClass<5> mysubclass; 
// type should be fixed to int, e.g. mysubclass can do the same like mybase 

Regards

Upvotes: 1

Views: 292

Answers (2)

Andreas H.
Andreas H.

Reputation: 6105

How about

template <int size>
using SubClass = BaseClass<int,size>;

It is not a subclass but, as far as I understand, does what you need. True subclass would be

template <int size>
class SubClass: public BaseClass<int,size> {
   ...
};

Upvotes: 5

songyuanyao
songyuanyao

Reputation: 173024

You can define the derived class as

template <int size> 
class SubClass : public BaseClass<int, size> {
    ...
};

Then for SubClass<5>, the base class specialization would be BaseClass<int, 5>.

Upvotes: 3

Related Questions