Is constexpr supported with lambda functions / expressions?

struct Test { static const int value = []() -> int { return 0; } (); }; 

With gcc-4.6, I get something like error: function needs to be constexpr . I tried several combinations of placing constexpr in different places, but no luck.

Is constexpr for lambda functions (no matter what type of return is specified or not)? What is the correct syntax?

Any job possible?

+44
c ++ lambda c ++ 11 constexpr
Jun 21 2018-11-11T00:
source share
4 answers

Update : with C ++ 17 lambdas in constant expressions are allowed.




Lambdas are currently (C ++ 14) not allowed in constant expressions according to [expr.const] / (2.6), but they will be sometime N4487 (which can be found in working draft N4582):

This proposal suggests using lambda expressions in constant expressions that eliminate the existing constraint. The authors suggest that some lambda expressions and operations on some closure objects can be displayed in constant expressions. At the same time, we also suggest that the type of closure be considered an alphabetic type if the type of each of its data elements is a literal type; and, if the constexpr specifier is not indicated in the lambda declarator, that the generated operator call the constexpr function if it satisfies the requirements of the constexpr function (similar to constexpr , which already occurs for implicitly defined constructors and functions of the assignment operator).

+22
Sep 21 '15 at 14:06
source share

From C ++ 0x FDIS ยง7.1.5 [dcl.constexpr] / 1:

The constexpr should only apply to a variable definition, function declaration or function template, or declaration of a static literal data element.

A lambda expression is not one of these things and therefore constexpr cannot be declared.

+24
Jun 21 2018-11-11T00:
source share

Prior to C ++ 17, lambdas are not compatible with constexpr . They cannot be used inside constant expressions.

Starting with C ++ 17 lambdas constexpr , where that makes sense. Proposal N4487 will be placed in the C ++ 17 standard. Herb Sutter, chairman of the ISO C ++ committee, stated on his website the following:

Lambdas are now allowed inside constexpr functions .

+9
Aug 09 '16 at 10:35
source share

FFWD until 2018 :)

 auto my_const_expression_lambda = []() constexpr -> bool { return true ; } 

Since C ++ 17

+1
Feb 23 '18 at 23:39
source share



All Articles