Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

c++ - How can I implement a map with different data types as values?

I want to put two (not more) different data types as values into a map as shown in the following example:

typeX A, B, ...;
typeY Z, Y, ...;

void func (typeX) { ... }
void func (typeY) { ... }

std::map <std::string, what_to_put_here??> map;
map["a"] = A;
map["z"] = Z;
...

std::vector<std::string> list;
// This list will be something like "a", "y", ...

for (unsigned int i = 0; i < list.size(); ++i)
    func( map[list[i]] )

Obviously this doesn't work, as the map will only accept one data type of value. However, when looping over list, the call to func() should be unambiguous since the type of map[list[i]] is known.

I want to avoid explicit casting or type checking, i.e. something like this:

if (typeid( map[list[i]] ).name() == "typeX")
    func( map[list[i]] )
else if (typeid( map[list[i]] ).name() == "typeY")
    func( map[list[i]] )

Is this possible? Again, it will be limited to only two different data types.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You want to use boost::variant:

std::map <std::string, boost::variant<typeX, typeY>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...