C ++在数组中存储具有不同模板的相同类

2022-01-24 00:00:00 arrays containers templates c++

我有以下课程:

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

但是std::vector;array; 不起作用,因为我显然需要指定一个模板,但我不能这样做,因为我在这个数组中存储了不同的类型.是否有某种泛型类型或其他解决方案?

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?

推荐答案

你需要一个基类:

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

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

然后像这样使用它

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

相关文章