使用不同数据类型的C ++映射作为值 [英] C++ map with different data types as values

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

问题描述

我的问题如下:我想把两个(没有更多)不同的数据类型作为值映射到地图。

my problem is as follows: I want to put two (no more) different datatypes as values into a map.

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 sth. 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. 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 typechecking, i.e. sth like

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

你能告诉我这是否可能吗?同样,它将仅限于两种不同的数据类型。感谢!

Can you tell me if this is possible? Again, it will be limited to only two different data types. Thanks!

推荐答案

您要使用 boost :: variant

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

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

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