Bluejay
Bluejay

Reputation: 351

Initialising constexpr - " illegal initialization of 'constexpr' entity with a non-constant expression"

I have two enum class types: Type and SocketType. The following code won't compile and fails with the message mentioned in the question, in VC++ 2017:

static constexpr std::map<Type,SocketType> PacketTypeMap =
    {
        {Type::JUSTJOINED,      SocketType::TCP},
        {Type::CHAT_MESSAGE,    SocketType::TCP},
        {Type::REQUEST_WORLD,   SocketType::TCP},
        {Type::DATA_WORLD,      SocketType::TCP},
        {Type::DATA_PLAYER,     SocketType::UDP},
        {Type::RESPAWN_PLAYER,  SocketType::TCP}
    };

Been trying some variations and nothing works, but I'm sure I'm just missing something simple with the syntax.

Upvotes: 4

Views: 1883

Answers (2)

Julius
Julius

Reputation: 1861

std::map is not compatible with constexpr. There exists an experimental(?) library called frozen, which provides a constexpr-compatible frozen::map (besides frozen::unordered_map, frozen::string, and others).

However, most probably you just want to pick a simpler solution (e.g., a switch statement in a constexpr function).

Upvotes: 4

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Migrating the answer from the comments section into the answer section.

There are no constexpr maps. It uses dynamic allocation, which is not possible with constexpr. Get rid of constexpr, or use a different container for compile-type map.

Upvotes: 3

Related Questions