GCC constexpr lambas in constexpr function and compile-time evaluation

First, the code has the following code fragment, which is used to accumulate constexpr std::array at compile time:

 template <typename T, std::size_t N, typename O> constexpr T compile_time_accumulator(const std::array<T, N> const &A, const std::size_t i, const O& op, const T initialValue) { return (i < N) ? op(A[i], compile_time_accumulator(A, i + 1, op, initialValue)) : initialValue; } 

and the following code example to check / modify it (i.e. what it evaluates at compile time):

 constexpr std::array<int, 4> v {{4, 5, 6, 7}}; std::cout << std::integral_constant<int, compile_time_accumulator(v, 42, std::plus<int>())>::value << std::endl; 

Live demo

Now, if you change the std::plus<int> operator using constexpr lambda:

 constexpr auto lambda_plus = [] (int x, int y) { return x + y; }; 

and name it as shown below:

 constexpr std::array<int, 4> v {{4, 5, 6, 7}}; std::cout << std::integral_constant<int, compile_time_accumulator(v, 42, lambda_plus)>::value << std::endl; ^^^^^^^^^^^ 

I get an error that lambda is not constexpr :

non-constexpr function call ''

Now, doing a litle study , I found that constexpr lambdas are not yet supported.

Q

Why, if constexpr lambdas are not supported, are we allowed to primarily define constexpr lambda?

Edit:

It seems that clang is not using code . So which compiler is right?

0
c ++ lambda c ++ 11 c ++ 14 constexpr
source share
2 answers

The code is really poorly formed according to [expr.const] / (2.6); lambdas are not yet permitted in constant expressions, although the corresponding sentence is outstanding. GCC is lambda_plus in accepting lambda_plus .

+3
source share

C ++ 11 allows a very limited definition of the amount of constexpr , while C ++ 14 has a long list of non- constexpr

From n4296 (candidate for release for C ++ 14) 5.20.2.6

5.20 Constant Expressions [expr.const]

2 The conditional expression e is an expression of a constant constant, the estimate e, following the rules of the abstract machine (1.9), will evaluate one of the following expressions:

2.6) - lambda expression (5.1.2);

So the answer is that the lambda is not in order, so the compiler should be wrong.

+3
source share

All Articles