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

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.


Solution 1:

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.

Solution 2:

Well, the first question would be: Why do you think you need to store objects of different, totally unrelated types in the same container? That seems fishy to me.

If I had the need, I'd look into boost::variant or boost::any.

Solution 3:

What you want is called a "hetrogenious container". C++ doesn't technically support them in the STL, but Boost does.

Given that, I think you'll find your answer in this question: how-do-you-make-a-heterogeneous-boostmap