Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 366
MarcDefiant Avatar asked Sep 09 '25 23:09

MarcDefiant


1 Answers

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>);
like image 135
Vaughn Cato Avatar answered Sep 12 '25 12:09

Vaughn Cato