类包含带有模板对象的容器 [英] Class containing container with template objects

查看:82
本文介绍了类包含带有模板对象的容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我上课

class A{
vector<B> arr;
};

其中

template <class T>
class B{
T member;
};

如何希望能够做类似的事情

How want to be able to do something like

A container;
B<int> b1;
B<char> b2;
...
container.arr.push_back(b1);
container.arr.push_back(b2);

我尝试在A类之前添加模板,但是我不想通过A类指定模板,因为那样我将不能推送不同类型的对象.我应该如何处理?

I tried adding template before class A, but i do not want to have to specify the template by class A, because then I wont be able to push objects of different types. How am I supposed to deal with this?

推荐答案

template是编译时代码生成结构.在您的代码示例中,B不是 type ,而是 template .

A template is a compile-time code generation construct. In your code examples, B is not a type, but a template.

模板以生成类型(例如B<int>).

Templates can be instantiated at compile-time to generate a type (e.g. B<int>).

std::vector<T>是在T上参数化的容器模板类-它只能存储类型为T的对象.

std::vector<T> is a container template class parametrized on T - it can only store objects of type T.

如果要将不同类型的对象存储在同一容器中,则可以:

If you want to store objects of different types in the same container, you can:

  • 如果在编译时知道对象序列,请使用std::tuple<Ts...>

如果在运行时不知道对象是A还是B,请使用std::vector<std::variant<A, B>>之类的东西.

Use something like std::vector<std::variant<A, B>> if you don't know whether an object is A or B until run-time.

这篇关于类包含带有模板对象的容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆