constexpr 算法 all_of 编译器错误

constexpr algorithm all_of compiler error

我有这么一小段代码:

void all_of_examples() {
  using std::begin;
  using std::end;

  //C++17 
  //template< class InputIt, class UnaryPredicate >
  //constexpr bool all_of( InputIt first, InputIt last, UnaryPredicate p );

  constexpr auto v2 = std::array<int, 4>{1, 1, 1, 1};
  constexpr auto eqOne = [](int x) constexpr { 
                          constexpr int one = 1;
                          return x == one; 
                       };

  constexpr bool isAllV2 = std::all_of(begin(v2), end(v2), eqOne);

  std::cout << isAllV2 << std::flush << '\n';
}

gcc-8 发出诊断(clang 也发出类似的错误):

examples.cpp:21:41: error: call to non-'constexpr' function 'bool std::all_of(_IIter, _IIter, _Predicate) [with _IIter = const int*; _Predicate = algo::all_of_examples()::]' constexpr bool isAllV2 = std::all_of(begin(v2), end(v2), eqOne);

我知道自 C++17 以来的 lamda 可以是 constexpr,而且 std::begin && std::end 都被标记为 constexpr。此外,std::array 也可以是 constexpr。因此,为什么编译器不选择 std::all_of 的 constexpr 版本并抱怨它不是?

从 c++20 开始,

std::all_of 只是 constexpr。另外 libstdc++ 还不支持这个。

libc++ 从 llvm-7 开始支持,但即使在使用 clang 时你可能仍然使用 libstdc++。

参见: