Xo *_*ang 12 c++ constexpr c++11 stdarray c++14
当我发现你不能在C++ 11中使用元素作为初始化器时,我正在将一些值填充到a中constexpr std::array,然后将编译时静态良好constexpr值继续为更多值constexpr.
这是因为在C++ 14之前std::array::operator[]实际上没有标记constexpr: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
Run Code Online (Sandbox Code Playgroud)
但有时我想在constexpr计算中使用临时数组,但这不起作用.
// Initialize a constexpr from a temporary
constexpr int b = std::array<int, 1>{{3}}[0]; // Doesn't work!
Run Code Online (Sandbox Code Playgroud)
我从clang ++ 3.6中得到了这个-std = c ++ 14:
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.
Run Code Online (Sandbox Code Playgroud)
我正在索引的两个变量之间有什么区别?为什么我不能使用直接初始化临时std::array的operator[]作为constexpr?
array你的第二个例子中的临时本身不是const,所以你最终调用非const operator[]重载,而不是constexpr.你可以让你的代码工作,如果你先投array来const.
constexpr int b = static_cast<std::array<int, 1> const&>(std::array<int, 1>{{3}})[0];
Run Code Online (Sandbox Code Playgroud)