我有一个地图,其中字符串表示属性的名称,第二个值表示该属性应具有的类型。
map.insert(make_pair("X", iDatatype::iUint));
map.insert(make_pair("Y", iDatatype::iUint));
map.insert(make_pair("RADIANT", iDatatype::iFloat));
其中iDatatype只是所有可能类型的枚举。
typedef enum
{
iUnknown = 0,
iByte = 1,
iChar = 2,
iUChar = 3,
iShort = 4.....
} iDatatype;
如果程序获得创建命令,例如“RADIANT”而不是查看地图,请找到iDatatype值(iter-> second)并转到切换案例。
switch (iter->second) {
case iDatatype::iUint:
uint value = ......
// You gotta do what you gonna do
break;
} .......
在Switch case中,将调用依赖于属性类型的函数。
此代码有效。但我不确定,如果它是使用类型映射字符串的最佳解决方案。 而我不知道应该寻找的问题是什么?您能否推荐一些常用的方法或技术?非常感谢你。
答案 0 :(得分:3)
除非你需要地图用于其他参考,否则另一种方法是:
if(command == "X" || command == "Y") // make sure command is std::string
// or use strcmp
{
// create uint
}
else if(command == "RADIANT")
{
// create float
}
但是我不确定这比使用地图要快多少,因为地图使用二进制搜索,而使用迭代搜索。
如果你想获得二进制搜索的增强而不需要另一个枚举,你可以使用函数映射:
std::map<std::string, std::function<void()> map;
map.insert(make_pair("X", &create_uint));
map.insert(make_pair("Y", &create_uint));
map.insert(make_pair("RADIANT", &create_float));
后来称之为:
std::string key = "X";
map[key]();
您也可以将参数传递给它,如:
void create_uint(std::string param) { /* ... */ }
std::map<std::string, std::function<void(std::string)> map;
map.insert(make_pair("X", &create_uint));
std::string key = "X";
std::string param = "XYZ";
map[key](param);