[英]Initialising constexpr - “ illegal initialization of 'constexpr' entity with a non-constant expression”
I have two enum class
types: Type and SocketType. 我有两种
enum class
类型:Type和SocketType。 The following code won't compile and fails with the message mentioned in the question, in VC++ 2017: 在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. 一直在尝试一些变体,但没有任何效果,但是我敢肯定,我只是在语法上缺少一些简单的东西。
Migrating the answer from the comments section into the answer section. 将答案从评论部分迁移到答案部分。
There are no constexpr maps.
没有constexpr映射。 It uses dynamic allocation, which is not possible with constexpr.
它使用动态分配,而constexpr则无法实现。 Get rid of constexpr, or use a different container for compile-type map.
摆脱constexpr,或对编译类型映射使用其他容器。
std::map
is not compatible with constexpr
. std::map
与constexpr
不兼容。 There exists an experimental(?) library called frozen , which provides a constexpr
-compatible frozen::map
(besides frozen::unordered_map
, frozen::string
, and others). 存在一个实验(?)库称为冷冻 ,它提供了一个
constexpr
兼容frozen::map
(除frozen::unordered_map
, frozen::string
,等等)。
However, most probably you just want to pick a simpler solution (eg, a switch
statement in a constexpr function). 但是,很可能您只是想选择一个更简单的解决方案(例如,constexpr函数中的
switch
语句)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.