Sebastian Dusza
Sebastian Dusza

Reputation: 2528

C++ templates and inheritance

can I mix inheritance and templates this way ? :

template <class T> 
class AbstractType { // abstract
//....
}

template <class T> 
class Type1 : public AbstractType<T> {
//....
}

And later on, can I use these classes like this:

AbstractType<SomeClass>* var1 = new Type1<SomeClass>();

Thx for help.

Upvotes: 4

Views: 1450

Answers (3)

John Dibling
John Dibling

Reputation: 101506

You can, but it's not going to be as useful as you may think. You can define the structures like this:

#include <string>
#include <vector>
using namespace std;

template<typename Val>
class Base
{
public:
    virtual Val DoIt() const = 0;
};

template<typename Val>
class Derived : public Base<Val>
{
public:
    Derived(const Val& val) : val_(val) {};
    Val DoIt() const { return val_; }
protected:
    Val val_;
};

int main()
{
    Derived<string> sd("my string");
    string sd_val = sd.DoIt();

    Derived<float> fd(42.0f);
    float fd_val = fd.DoIt();
}

But when you're defining abstract base types, you're often going to want a collection of them, and to be able to call through a base class pointer to get polymorphic behavior. If you templatize the base class, you're not going to be able to do this because each variation of the template parameters will create a different type. Base<int> is completely different than Base<string>, and you can't just get a Base* that points to either one.

This code will not compile:

vector<Base*> my_objs;

Upvotes: 7

Chubsdad
Chubsdad

Reputation: 25537

You can use any type with the class template, provided the type is compatible with the class definition

e.g.

template<class T> struct S{
   T mt;
};

Such a struct can be instantiated for T = int, T = double, but not T = void.

Upvotes: 1

sharptooth
sharptooth

Reputation: 170549

Yes, you can. You can use the template parameter for whatever you want, passing into the base templated class included.

Upvotes: 7

Related Questions