4
votes

I have this small piece of code:

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 issues a diagnostic(clang issues a similar error as well):

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);

I know that lamdas since C++17 can be constexpr and also std::begin && std::end are both marked as constexpr. Furthermore, std::array can also be constexpr. Therefore, why the compiler doesn't pick the constexpr version of std::all_of and complains that it isn't?

1
all_of is constrexp since C++20, have you used correct switch? - Radosław Cybulski

1 Answers

4
votes

std::all_of is only constexpr as of c++20. Also libstdc++ doesn't support this yet.

libc++ has support as of llvm-7 but even when using clang you probably still use libstdc++.

See: