是否有一个容器可以存储不同类型的项目? [英] Is there a container that can store items of different types?

查看:223
本文介绍了是否有一个容器可以存储不同类型的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

存储相同类型的项目是微不足道的,但我需要一个容器来存储不同类型的项目。

Storing items of the same type is trivial, but I need a container that can store items of different types.

这里有一个例子, do:

Here's an example showing what I'd like to do:

Class C
{
};

C c1;
C c2;
C c3;

std::tuple<C> tup1(c1);
std::tuple<C, C> tup2(c1, c2);
std::tuple<C, C, C> tup3(c1, c2, c3);

container_type container(tup1, tup2, tup3);

有没有任何容器以这种方式工作?如果没有,是否有办法创建一个?

Is there any container that works in this way? If not, is there a way to create one?

我想要重载 operator [] 快速随机存取。

I'd like something that overloads operator[] for fast random access.

推荐答案

运行时多态性需要间接和多态类型。

Run-time polymorphism requires indirection and polymorphic types. What tuples, by their nature, aren't.

你可以做的是使你的对象成为继承层次结构的一部分,并存储在容器(智能)指针中动态分配的对象(动态分配是必要的,因为它们是不同类型的对象,它们也有不同的大小),或者将你的对象包装成一个类(如 boost :: any

What you can do is make your objects part of an inheritance hierarchy, and store in the container (smart)pointers to dynamically allocated objects (dynamic allocation is necessary, since being objects of different types they also have different sizes), or wrap your objects into a class (like boost::any, for example) that does "type cancellation", essentially by doing internally the indirection required).

在任何情况下,容器接口在执行此操作时,将访问指针或指针,包装。它取决于你在运行时检查每个被引用对象的实际类型,然后再访问它自己的特定函数,或者只依赖于所有公共的虚函数。

In any case, the container interface, when doing this, will access the pointers or the wrappers. It's up to you to check at runtime the actual type of each referred object before accessing its own specific functions, or to rely only to the virtual function that are common to all.

这篇关于是否有一个容器可以存储不同类型的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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