当我发现在 C++11 中不能使用元素作为初始化程序时,我正在将一些值填充到 a 中constexpr std::array
,然后将编译时静态特性继续添加到更多值中。constexpr
constexpr
这是因为std::array::operator[]
实际上constexpr
直到 C++14 才被标记:https ://stackoverflow.com/a/26741152/688724
编译器标志升级后,我现在可以使用 a 的元素constexpr std::array
作为constexpr
值:
#include <array>
constexpr std::array<int, 1> array{{3}};
// Initialize a constexpr from an array member through its const operator[]
// that (maybe?) returns a const int & and is constexpr
constexpr int a = array[0]; // Works in >=C++14 but not in C++11
但有时我想在constexpr
计算中使用临时数组,但这不起作用。
// Initialize a constexpr from a temporary
constexpr int b = std::array<int, 1>{{3}}[0]; // Doesn't work!
我从带有 -std=c++14 的 clang++ 3.6 得到这个:
prog.cc:9:15: error: constexpr variable 'b' must be initialized by a constant expression
constexpr int b = std::array<int, 1>{{3}}[0]; // Doesn't work!
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~
prog.cc:9:19: note: non-constexpr function 'operator[]' cannot be used in a constant expression
constexpr int b = std::array<int, 1>{{3}}[0]; // Doesn't work!
^
/usr/local/libcxx-3.5/include/c++/v1/array:183:41: note: declared here
_LIBCPP_INLINE_VISIBILITY reference operator[](size_type __n) {return __elems_[__n];}
^
1 error generated.
我要索引的两个变量之间有什么区别?为什么我不能使用直接初始化的std::array
临时operator[]
as constexpr
?