类包含带有模板对象的容器 [英] Class containing container with template objects
问题描述
我上课
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屋!