Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 have tried multiple combinations of putting constexpr at various places, but no luck.

Is constexpr supported for lambda functions as well (irrespective of return type specified or not) ? What is the correct syntax ?

Any work around possible ?

like image 415
iammilind Avatar asked Jun 21 '11 03:06

iammilind


People also ask

Can a lambda be constexpr?

Visual Studio 2017 version 15.3 and later (available in /std:c++17 mode and later): A lambda expression may be declared as constexpr or used in a constant expression when the initialization of each data member that it captures or introduces is allowed within a constant expression.

Are lambdas Inlined?

All lambdas are inline. Not all calls to them are necessarily inlined.

Can lambda expression contain statements?

In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body. It is written as a single line of execution.


1 Answers

Update: As of C++17, lambdas are permitted in constant expressions.


Lambdas are currently (C++14) not allowed in constant expressions as per [expr.const]/(2.6), but they will once N4487 is accepted (which can be found in the working draft N4582):

This proposal suggests allowing lambda-expressions in constant expressions, removing an existing restriction. The authors propose that certain lambda-expressions and operations on certain closure objects be allowed to appear within constant expressions. In doing so, we also propose that a closure type be considered a literal type if the type of each of its data-members is a literal type; and, that if the constexpr specifier is omitted within the lambda-declarator, that the generated function call operator be constexpr if it would satisfy the requirements of a constexpr function (similar to the constexpr inference that already occurs for implicitly defined constructors and the assignment operator functions).

like image 172
Columbo Avatar answered Oct 04 '22 16:10

Columbo