C++ c++;属性的映射类型

C++ c++;属性的映射类型,c++,map,C++,Map,我有一个映射,其中字符串表示属性的名称,第二个值表示该属性应该具有的类型 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, iBy

我有一个映射,其中字符串表示属性的名称,第二个值表示该属性应该具有的类型

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;
例如,如果程序获得了创建“辐射”的命令,那么它可以查看地图,找到iDatatype值(iter->second)并转到switch case

 switch (iter->second) {
           case iDatatype::iUint:
           uint value = ......
            // You gotta do what you gonna do
            break;
              } .......
在开关情况下,将调用函数,该函数取决于属性的类型

这个代码有效。但我不确定,将字符串映射到类型是否是最好的解决方案。
问题是我不知道该找什么?你能推荐哪些方法或技术常用于此目的吗?非常感谢。

除非您需要地图作为其他参考,否则另一种方法是:

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));
您还可以向其传递参数,如:

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);
void create_uint(std::string param){/*…*/}

std::mapAnd一次又一次:我知道它是官方的,但由于C++11及其实现编译器的年龄还很小,所以对
std::function
的C++11特性稍作介绍是合适的。不是每个人都知道,您需要最新的gcc/VS/where来使用它。当然,我不是说“不要使用C++11功能”,而是“提及它们本身”。@ChristianRau:只是它的新功能并不意味着你需要爬到岩石下面,尽可能多地使用C++1234BC功能,并总是警告新功能。不,使用它,这是个好主意。但是不要期望新手(虽然这不需要为OP来保持)来了解C++标准化过程,或者他的下一个问题是“为什么我的编译器找不到代码> STD::Fuff< /Cord>?”.@ CythRayu:某人可能也会使用Turbo C++。我(和我相信大部分网站)希望看到的至少是HTML兼容的混乱发生在C++上
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);