简体   繁体   English

字符串作为键和类型作为值的C ++映射

[英]C++ map of string as key and type as value

Is there an alternative to boost-hana in boost library which will allow me to create something like Boost库中是否有boost-hana的替代方法,这将允许我创建类似

typedef boost::AlterinativeToHana::map< make_pair<"abcd",ABCDType>,
                 make_pair<"efgh",EFGHType>,
                 make_pair<"ijkl",IJKLType>
               > stringToTypeMap;

I have used boost-fusion , but I could not find a proper solution for my use case ie character string to type mapping. 我使用了boost-fusion ,但是找不到适合我的用例的解决方案,即字符串到类型的映射。

I think std::type_index is what you need: 我认为std :: type_index是您需要的:

#include <iostream>
#include <typeindex>
#include <map>

class A
{};

class B
{};

int main()
{   
    std::map<std::type_index, std::string> typesMap;
    typesMap[typeid(A)] = "1111";
    typesMap[typeid(B)] = "2222";

    A instA;
    B instB;

    cout << "instA: " << typesMap[typeid(instA)] << "\n";
    cout << "instB: " << typesMap[typeid(instB)] << "\n";

    return 0;
}

Output: 输出:

instA: 1111
instB: 2222

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM