C++ store same classes with different templates in array

主宰稳场 提交于 2019-12-29 06:31:49

问题


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?


回答1:


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>);


来源:https://stackoverflow.com/questions/13345595/c-store-same-classes-with-different-templates-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!