Class containing container with template objects

穿精又带淫゛_ 提交于 2019-12-11 17:31:02

问题


I have a class

class A{
vector<B> arr;
};

where

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

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?


回答1:


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

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


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:

  • Use std::tuple<Ts...> if you know the object sequence at compile-time;

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




回答2:


As mentioned in some comments, storing variables of distinct types into a std::vector might not be a good idea, and in fact, if you need to do so, chances are these types have something in common such that you can find more suitable approaches for achieving your goals, such as creating a std::vector<std::unique_ptr<Base_Type>>.

However, what you tried to do is still possible in a slightly different way using std::any.

template <typename T>
struct B
{
    T member;
};
// ...
std::vector<std::any> v;
B<int>  bi {123};
B<char> bc {'@'};
B<std::string> bs {"I am a string"};

v.push_back(bi);
v.push_back(bc);
v.push_back(bs);

// Go through vector. You will have to check for the type and
// cast it appropriately before doing anything useful.
for (auto x : v) {
    if (x.type() == typeid(B<int>))
        std::cout << std::any_cast<B<int>>(x).member << std::endl;
    else if (/* ... */)
        // ...
}
// ...

Another option could be a std::vector of std::variants, as explained by Vittorio.



来源:https://stackoverflow.com/questions/50642933/class-containing-container-with-template-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!