How can I store objects of differing types in a C++ container?

Ramsey picture Ramsey · Jan 19, 2011 · Viewed 49.5k times · Source

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;

I'm restricted with the format:

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

which forces mycontainer to only consist of one type.

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.

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.

[edit] Hey guy, many thanks for your suggestions - I should explain how I'll use this container, but it's a tad complicated hence the (big) simplification above. I think the best option from here is using the Boost. Thanks again.

Answer

user197015 picture user197015 · Jan 19, 2011

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.