gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:15:22 25 4
gpt4 key购买 nike

我有以下类(class):

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

现在我需要一个具有不同模板的此类实例数组,例如:

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

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

最佳答案

你需要一个基类:

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

关于C++ 在数组中存储具有不同模板的相同类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13345595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com