gpt4 book ai didi

c++ - 在数组中保存模板类对象

转载 作者:太空宇宙 更新时间:2023-11-04 15:01:55 24 4
gpt4 key购买 nike

我必须为我的项目在一个数组中保存不同类型的数据。我创建了一个用于生成对象的模板类。

template<class Queue>
class Template {

public:
Queue value;
Template(Queue input) {
value = input;
}

};

但我不能在不使用抽象类的情况下将它们保存在一个数组中。我为此创建了一个空指针数组。我喜欢它;

void *array[21];
array[index] = new Template<int>(number);
array[index] = new Template<string>(text);

没有抽象类有没有可能的解决方案?我的意思是,我可以将这个模板对象保存在模板类的数组中吗?

最佳答案

创建层次结构并利用动态绑定(bind):

class Base  {
public:
virtual ~Base() {};
// ...
};

template<class Queue>
class Template : public Base {
Queue value;
public:
Template(Queue const &input) :value(input) {}
// ...
};

并将其用作:

Base *array[21];
array[index] = new Template<int>(number);
array[index + 1] = new Template<string>(text);

此外,不要使用原始数组和原始指针,而是使用像 std::array 这样的 STL 工具智能指针(例如 std::shared_ptr<Base>std::unique_ptr<Base> ):

std::array<std::unique_ptr<Base>, 21> arr;
arr[index].reset(new Template<int>(number));
arr[index + 1].reset(new Template<string>(text));

也更喜欢将成员变量初始化到构造函数的初始化列表而不是它的主体。

关于c++ - 在数组中保存模板类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33507697/

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