如何在 C++ 容器中存储不同类型的对象? [英] How can I store objects of differing types in a C++ container?

查看:79
本文介绍了如何在 C++ 容器中存储不同类型的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有我可以使用或构建的 C++ 容器,它可以包含例如 intstringdouble 类型?我面临的问题是,每当我尝试使用以下内容填充地图、向量或列表时:

Is there a C++ container that I could use or build that can contain, say, int and string and double types? The problem I'm facing is that whenever I try to populate, say, a map, vector or list with, say, the following:

int x;
string y;
double z;

我受格式限制:

list<int> mycountainer;
vector<string> mycontainer;

强制 mycontainer 只包含一种类型.

which forces mycontainer to only consist of one type.

在有人建议泛型之前,这也行不通,因为 C++ 附带的标准 vectorlist 容器已经是通用的 -它们可以是任何类型的容器,但不能包含多种类型.

Before anyone suggest generics, that wouldn't work either since the standard vector and list containers that come with C++ are already generic - they can be container for any types but cannot contain multiple types.

如果可能的话,我也想避免使用 Boost - 如果有一种我可以自己编写代码的简单方法,我会更喜欢它.

I would like to avoid using Boost also if at all possible - I'd prefer it if there is a simple way I could code this myself.

推荐答案

您可以使用(或重新实现)boost::any 并存储 boost::any 的实例代码> 在容器中.那将是最安全的,因为 boost::any 可能已经处理了在一般情况下解决此类问题所涉及的许多边缘情况和复杂性.

You could use (or re-implement) boost::any and store instances of boost::any in a container. That would be the safest, since boost::any has probably dealt with much of the edge cases and complexity involved in solving this kind of problem in the general case.

如果您想做一些快速而肮脏的事情,请创建一个结构或一个联合,其中包含所有潜在类型的成员以及对象中哪种类型是活动的"的枚举或其他指示符.使用联合时要特别小心,因为它们有一些有趣的属性(例如,如果您读错了联合成员,则会调用未定义的行为,一次只能活动"一个成员,即最近写入的成员).

If you want to do something quick and dirty, create a structure or perhaps a union containing members of all potential types along with an enumeration or other indicator of which type is 'active' in the object. Be especially careful with unions as they have some interesting properties (such as invoking undefined behavior if you read the wrong union member, only one of the members can be 'active' at a time, the one that was most recently written to).

我很好奇你在做什么,你需要这样一个构造.

I'm curious what you're doing that you need such a construct, though.

这篇关于如何在 C++ 容器中存储不同类型的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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