Constexpr with Lambda Functions: Current Status and Future Prospects
In C , constexpr enables compiler evaluation of expressions at compile time. However, its support for lambda functions has been a topic of interest.
Historically, C 14 prohibited lambda functions within constant expressions. Attempts to force constexpr in various contexts proved unsuccessful.
However, significant progress has been made with C 17's acceptance of N4487. This proposal allows lambda expressions in constant expressions under specific conditions:
1. Correct Lambda Expression Syntax:
When using lambdas with constexpr, ensure the lambda is declared as constexpr. This informs the compiler that the lambda should be treated as a constant expression.
2. Closure Type as Literal Type:
For lambda expressions to be used in constant expressions, their closure type (the type of the object created by the lambda) must be a literal type. This means all its data members must also be literal types.
3. Constexpr Inference:
If the lambda declaration omits the constexpr specifier, the function call operator is inferred to be constexpr provided it meets the requirements of a constexpr function. Similarly to implicit constructors and assignment operators.
4. Future Prospects:
With C 17's implementation, lambda functions can now be used in constant expressions. As C evolves, future revisions may expand this support further, potentially allowing more complex and versatile use cases for lambdas in constant-time scenarios.
The above is the detailed content of Can Lambda Functions Be Used in Constexpr in C ?. For more information, please follow other related articles on the PHP Chinese website!