C++ Map with multiple data types?

Hi everyone!

I'm doing a C++ problem that I'm a bit stuck on.

I'd like to be able to store multiple data types in a C++ container with a key (such as a Map)...

Is there any way to do this or another way I should be approaching this?

Thanks
You could use a data structure that has all the data types you will need. Something like this:
1
2
3
4
5
6
7
8
struct dtypes{
         int i;
         string str;
         double d;
};

int main(){
     map<dtypes>;


You can set only the values per structure within the map that you want to actually use, You'll have some garbage variables and use extra memory though. What exactly are you doing, can you use a different map for each type?
If the above doesn't do the trick for you, I believe boost::any does what you're asking for ( http://www.boost.org/doc/libs/1_40_0/doc/html/any.html ). Personally I've never used it, so I can't say how well it works or even if it's what you're asking for, but you may want to have a look at it.
As joshky says it is a matter of declaring a case (or struct) with the appropriate methods
If you want the same map to point to one type at position 0 let's say and another type at position 1 you could do something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<map>
class Base{
//class members
}

class Derived : public Base{
//class members
}

int main{
    std::map<anything, Base> mymap;
    Base b;
    Derived d;
    mymap.insert(std::pair<anything, Base>(anything_data, b));
    mymap.insert(std::pair<anything, Base>(anything_data, d));

    //more code
}


You would of course replace "anything" with a typename.
The derivation thing is OK; it works albeit at the expense of forcing the user to derive their types from some base type.

boost::any is also OK, but may not fit the bill -- the problem is that you have to know the contained type in order to retrieve it, and based on the limited information above, you don't.

boost::variant is good -- it is the C++ equivalent of a union -- but has a limitation on the number of types that can be stored (unless you change a #define in the boost library) and is also limited in the sense that you must know at compile time all of the types that will be stored.

Otherwise you don't really have any other reasonable options for a polymorphic container.

Using the derivation thing with a template subclass seems to work nicely...

Topic archived. No new replies allowed.