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

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.


You can use either structures, or classes or std::pair.

[edit]

For classes and structs:

struct XYZ {
    int x;
    string y;
    double z;
};
std::vector<XYZ> container;

XYZ el;
el.x = 10;
el.y = "asd";
el.z = 1.123;
container.push_back(el);

For std::pair:

#include <pair>
typedef std::pair<int, std::pair<string, double> > XYZ;
std::vector<XYZ> container;
container.push_back(std::make_pair(10, std::make_pair("asd", 1111.222)));

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


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.