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

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.

Leave a Comment