C++将不同数据类型映射为值

use*_*855 6 c++ polymorphism dictionary stdmap

我的问题如下:我想将两个(不多)不同的数据类型作为值放入映射中.

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]] )
Run Code Online (Sandbox Code Playgroud)

显然这不起作用,因为地图只接受一种数据类型的值.当循环"list"时,对"func"的调用应该是明确的,因为map [list [i]]的类型是已知的.

我想避免显式转换或类型检查,即......

if (typeid( map[list[i]] ).name() == "typeX")
    func( map[list[i]] )
else if (typeid( map[list[i]] ).name() == "typeY")
    func( map[list[i]] )
Run Code Online (Sandbox Code Playgroud)

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

Pau*_*ans 4

你想使用boost::variant

std::map <std::string, boost::variant<typeX, typeY>>
Run Code Online (Sandbox Code Playgroud)