如何实现将不同数据类型作为值的映射? [英] How can I implement a map with different data types as values?

查看:126
本文介绍了如何实现将不同数据类型作为值的映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将两种(而不是更多种)不同的数据类型作为值放入映射中,如以下示例所示:

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]] )

显然这是行不通的,因为映射将仅接受值的一种数据类型.但是,在循环遍历list时,对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.

推荐答案

您要使用 boost::variant :

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

这篇关于如何实现将不同数据类型作为值的映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆