【发布时间】:2015-10-19 19:34:25
【问题描述】:
当我发现在 C++11 中不能将元素用作 constexpr 初始值设定项时,我正在将一些值填充到 constexpr std::array 中,然后将编译时静态特性继续添加到更多 constexpr 值中.
这是因为 std::array::operator[] 实际上直到 C++14 才标记为 constexpr:https://stackoverflow.com/a/26741152/688724
编译器标志升级后,我现在可以使用 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[] 用作constexpr?
【问题讨论】:
标签: c++ c++11 c++14 constexpr stdarray