In Java, you can have a List of Objects. You can add objects of multiple types, then retrieve them, check their type, and perform the appropriate action for that type.
For e
boost::variant is similar to dirkgently's suggestion of boost::any
, but supports the Visitor pattern, meaning it's easier to add type-specific code later. Also, it allocates values on the stack rather than using dynamic allocation, leading to slightly more efficient code.
EDIT: As litb points out in the comments, using variant
instead of any
means you can only hold values from one of a prespecified list of types. This is often a strength, though it might be a weakness in the asker's case.
Here is an example (not using the Visitor pattern though):
#include
#include
#include
using namespace std;
using namespace boost;
...
vector > v;
for (int i = 0; i < v.size(); ++i) {
if (int* pi = get(v[i])) {
// Do stuff with *pi
} else if (string* si = get(v[i])) {
// Do stuff with *si
} else if (bool* bi = get(v[i])) {
// Do stuff with *bi
}
}
(And yes, you should technically use vector
instead of int
for i
's type, and you should technically use vector
instead anyway, but I'm trying to keep it simple.)