我试图声明一个constexpr指针初始化为一些常量整数值,但clang正在挫败我所有的尝试:
尝试1:
constexpr int* x = reinterpret_cast<int*>(0xFF);
test.cpp:1:20: note: reinterpret_cast is not allowed in a constant expression
Run Code Online (Sandbox Code Playgroud)
尝试2:
constexpr int* x = (int*)0xFF;
test.cpp:1:20: note: cast which performs the conversions of a reinterpret_cast is not allowed in a constant expression
Run Code Online (Sandbox Code Playgroud)
尝试3:
constexpr int* x = (int*)0 + 0xFF;
test.cpp:1:28: note: cannot perform pointer arithmetic on null pointer
Run Code Online (Sandbox Code Playgroud)
是我试图不允许的设计?如果是这样,为什么?如果没有,我该怎么办?
注意:gcc接受所有这些.
考虑以下代码:
struct foo {
static constexpr const void* ptr = reinterpret_cast<const void*>(0x1);
};
auto main() -> int {
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的例子在g ++ v4.9(Live Demo)中编译得很好,但它无法在clang v3.4(Live Demo)中编译并生成以下错误:
错误:constexpr变量'ptr'必须由常量表达式初始化
问题:
根据标准,哪两个编译器是正确的?
声明这种表达的正确方法是什么?