简体   繁体   English

初始化constexpr-“用非常量表达式非法初始化'constexpr'实体”

[英]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::mapconstexpr不兼容。 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_mapfrozen::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.

相关问题 C++ constexpr 函数实际上可以接受非常量表达式作为参数吗? - Can C++ constexpr function actually accept non-constant expression as argument? nvcc 错误:string_view.h:constexpr 函数返回非常量 - nvcc error: string_view.h: constexpr function return is non-constant 为什么允许一些非常量表达式作为constexpr逗号运算符的操作数? - Why are some non-constant expressions allowed as operands of a constexpr comma operator? 当值是非常量但使用常量表达式初始化时使用constexpr吗? - Using constexpr when a value is non-const but initialized with a constant expression? 使用constexpr进行constexpr文字初始化 - constexpr literal initialization with a constexpr constexpr和初始化 - constexpr and initialization 如果明确默认的constexpr ctor允许非constexpr初始化 - Should an explicitly defaulted constexpr ctor allow non-constexpr initialization 错误! constexpr 变量必须由常量表达式 constexpr 初始化 - Error! constexpr variable must be initialized by a constant expression constexpr Constexpr初始化不可复制对象数组? - Constexpr initialization of an array of non-copyable objects? constexpr - 函数不能用于常量表达式 - constexpr - function cannot be used in a constant expression
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM