使用constexpr编译时出错
Error compilation with constexpr
我正在尝试编译这段代码:
enum class Order : char
{
Little,
Big
};
constexpr Order get_order() {
uint16_t x = 1;
return *((uint8_t *) &x) == 0 ? Order::Big : Order::Little;
}
我用-std=c++14
标记,但我得到这个错误:
在函数constexpr byteorder::Order byteorder::get_order()中:/home/user/dev/c++/render/include/byteorder.h:19:1:错误:constexpr函数' constexpr byteorder::Order byteorder::get_order() '不是return-statement
如果c++14允许在constexpr函数中使用局部变量,这怎么可能发生呢?
clang说:
test.cpp:9:17: error: constexpr function never produces a constant expression
[-Winvalid-constexpr]
constexpr Order get_order() {
^
test.cpp:11:14: note: cast that performs the conversions of a reinterpret_cast
is not allowed in a constant expression
return *((uint8_t *) &x) == 0 ? Order::Big : Order::Little;
^
1 error generated.
从这里的GCC标准实现页面来看,这似乎只适用于GCC版本5及以上。
constexpr
说明符声明可以在编译时计算函数或变量的值。
你取了一个局部变量的地址(在运行时赋值),这意味着不可能在编译时对该表达式求值。
编辑:尽管如此,对于可能导致未定义行为的表达式,我们认为其不符合constexpr
要求的核心常数表达式和函数是受限制的。指针解引用可能属于这一类,或者使用reinterpret_cast
进行强制转换,这与传统的强制转换类似。
相关文章:
- 在Linux for Windows上编译C++代码时出错
- 为x86而非x64编译时出错
- 当我尝试通过 mingw 使用 CMake 和 SFML 库编译项目时出错
- 尝试在Windows上执行C++时出错(通过MinGW编译)
- 如何使用我构建的库,而不会从源代码出错,但不为我自己的项目编译?
- constexpr 使用 clang 编译 TensorFlow 时出错
- 从DLL导出函数,LoadLibrary()需要用TEXT转换的字符串才能编译而不会出错
- 编译包含指向模板函数的指针的初始值设定项列表时,gcc 出错,但 clang 不出错
- 编译时出错 - 从 DWORD 到 LPCVOID 的转换
- 在发布模式下启动使用库的静态链接编译的应用程序时出错
- 编译时出错 - 链接.cpp和头文件
- <limits> 使用 VSC2019 编译旧代码时出错
- 在 ubuntu 焦点上编译虚幻引擎 4.25 时出错
- 编译包含LLVM API标头的C++文件时出错
- 编译以下代码时出错
- 使用交叉工具ng编译gcc时出错
- 在 dll 中为 qLibrary 编译 qobject 时出错
- 使用 cmake 在窗口上编译 c++ 数据库时出错
- 使用 TDM GCC 5.1.0 编译 PDCurses36 时出错
- Lua :在原生lua中编译,但在使用LuaJIT和sol2时C++出错