4

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.

6
  • A std::map constructor is not constexpr. Its implementation is expected to require information not known until runtime. Commented Nov 30, 2018 at 18:30
  • 4
    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. Commented Nov 30, 2018 at 18:31
  • Hmm. I guess I should just use const instead in this case. Thanks! Commented Nov 30, 2018 at 18:31
  • @SergeyA Answers go not in comments, thanks Commented Dec 6, 2018 at 10:42
  • 1
    @LightnessRacesinOrbit I believe this doesn't reach to the quality of an answer. Good answer would suggested a constexpr friendly associative container with implementation. On the other hand, further clarification from OP indicates that they are not interested in compile-time map, just an immutable map... Anyway, thanks for the answer. Commented Dec 6, 2018 at 17:09

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.