初始化枚举到结构的映射

Initialize map of enums to structures

在 C++ 中,我试图将 std::map 个枚举值初始化为结构。

在头文件中:

enum ePrompts
{
    ePrompt1,
    ePrompt2,
    ...
};

enum eDataTypes
{
    eIntegers,
    eDoubles,
    ...
};

struct SomeInfo
{
    std::string text;
    eDataTypes type;
    float minVal;
    float maxVal;
};

std::map<ePrompts, SomeInfo> mInfoMap;

在cpp文件中:

void SomeClass::InitializeThis()
{    
    // I would like to have an approach that allows one line per entry into the map
    mInfoMap[ePrompt1] = (SomeInfo){"text1", eIntegers, 2, 9}; //Error: Expected an expression

    // Also tried
    SomeInfo mInfo = {"text1", eIntegers, 2, 9};
    mInfoMap[ePrompt1] = mInfo; // works
    mInfo = {"text2", eIntegers, 1, 5}; //Error: Expected an expression
}

我可能在这里遗漏了一些非常简单的东西,但我已经通过 Stack Overflow 进行了大量搜索,但没有得出有人这样做的任何结果。如有任何帮助,我们将不胜感激!

你的第一行有正确的想法。它只需要稍微改变一下:

mInfoMap[ePrompt1] = SomeInfo{"text1", eIntegers, 2, 9};

根据 C++ 标准(5.2.3 显式类型转换(函数符号))

3 Similarly, a simple-type-specifier or typename-specifier followed by a braced-init-list creates a temporary object of the specified type direct-list-initialized (8.5.4) with the specified braced-init-list, and its value is that temporary object as a prvalue

所以只写

mInfoMap[ePrompt1] = SomeInfo {"text1", eIntegers, 2, 9};