Home > Backend Development > C++ > body text

Can Lambda Functions Be Used with `constexpr` in C ?

Susan Sarandon
Release: 2024-11-02 09:51:02
Original
447 people have browsed it

Can Lambda Functions Be Used with `constexpr` in C  ?

Lambda Functions and Constexpr

Question: Is it possible to use constexpr with lambda functions in C ?

In the following code example, the compiler reports an error related to requiring a constexpr function:

<code class="cpp">struct Test
{
  static const int value = []() -> int { return 0; } ();
};</code>
Copy after login

Answer:

Update (C 17): As of C 17, lambda functions are allowed in constant expressions.

Pre-C 17: Lambdas are not currently permitted in constant expressions in C 14. However, a proposal (N4487) has been made to allow certain lambda expressions and closure objects to appear in constant expressions.

If this proposal is accepted, it would introduce the following changes:

  • Closure types would be considered literal types if their data members are all literal types.
  • If no constexpr specifier is provided in the lambda declarator, the generated function call operator would be constexpr if it meets the requirements for a constexpr function.

This change would align with the behavior of implicitly defined constructors and assignment operator functions, which can be inferred as constexpr when appropriate.

The above is the detailed content of Can Lambda Functions Be Used with `constexpr` in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template