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

Rec*_*ker 3 c++ boost-fusion boost-mpl c++11 boost-hana

在 boost 库中是否有boost-hana的替代方法,它可以让我创建类似的东西

typedef boost::AlterinativeToHana::map< make_pair<"abcd",ABCDType>,
                 make_pair<"efgh",EFGHType>,
                 make_pair<"ijkl",IJKLType>
               > stringToTypeMap;
Run Code Online (Sandbox Code Playgroud)

我使用了boost-fusion,但我找不到适合我的用例的正确解决方案,即字符串类型映射。

Dmi*_*lov 6

我认为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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

instA: 1111
instB: 2222
Run Code Online (Sandbox Code Playgroud)

  • 我实际上需要这里的反向映射,而不是你提到的。从 `std::string` 到定义良好的类型。 (2认同)