MarcDefiant
MarcDefiant

Reputation: 6889

C++ store same classes with different templates in array

I have the following class:

template <typename T>
class A
{
public:
    void method(const char *buffer);
    // the template T is used inside this method for a local variable
};

Now I need an array of instances of this class with different templates like:

std::vector<A*> array;
array.push_back(new A<uint32_t>);
array.push_back(new A<int32_t>);

But std::vector<A*> array; wont work, because I apparently need to specify a Template, but i can't so that because I store different types in this array. Is there some kind of generic type or an other solution?

Upvotes: 4

Views: 2857

Answers (1)

Vaughn Cato
Vaughn Cato

Reputation: 64298

You need a base class:

class ABase {
public:
    virtual void method(const char *) = 0;
    virtual ~ABase() { }
};

template <typename T>
class A : public ABase
{
public:
    virtual void method(const char *);
};

then use it like

std::vector<ABase*> array;
array.push_back(new A<uint32_t>);
array.push_back(new A<int32_t>);

Upvotes: 9

Related Questions