Initialize map of enums to structures

855 Views Asked by At

In C++, I am attempting to initialize a std::map of enumeration values to structures.

In the header file:

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

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

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

std::map<ePrompts, SomeInfo> mInfoMap;

In the cpp file:

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
}

I am probably missing something very simple here, but I have searched through Stack Overflow quite a bit and not come up with any results of someone doing this. Any help would be appreciated!

2

There are 2 best solutions below

6
On BEST ANSWER

Your first line had the right idea. It just needs a slight change:

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

According to the C++ Standard (5.2.3 Explicit type conversion (functional notation))

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

So just write

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