【发布时间】:2012-05-09 07:43:18
【问题描述】:
我正在尝试声明一个初始化为某个常量整数值的 constexpr 指针,但是 clang 正在挫败我的所有尝试:
尝试 1:
constexpr int* x = reinterpret_cast<int*>(0xFF);
test.cpp:1:20: note: reinterpret_cast is not allowed in a constant expression
尝试 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
尝试 3:
constexpr int* x = (int*)0 + 0xFF;
test.cpp:1:28: note: cannot perform pointer arithmetic on null pointer
我试图做的事情是设计不允许的吗?如果是这样,为什么?如果没有,我该怎么办?
注意:gcc 接受所有这些。
【问题讨论】:
-
这里为什么需要一个 constexpr?如果不使用函数, constexpr 是否与 const 实际上相同?
-
@RobertMason:嗯,例如,如果它是一个类的静态成员,而且它不是 constexpr,我就不能内联初始化它。
-
也许静态内联成员函数比数据成员更合适。
-
@HighCommander4:你不允许内联初始化整数吗?指针在下面是整数(不是全部),所以即使它不完全是标准的(我不知道,我没有标准的副本)你应该能够让大多数编译器接受它.
-
@RobertMason:clang 和 gcc 不接受非 constexpr 指针的内联初始化。我不知道为什么——我也想知道原因。
标签: c++ pointers c++11 clang constexpr