Home  >  Article  >  Backend Development  >  Can Lambda Functions Be Used in `constexpr` Contexts?

Can Lambda Functions Be Used in `constexpr` Contexts?

DDD
DDDOriginal
2024-10-31 00:30:29978browse

 Can Lambda Functions Be Used in `constexpr` Contexts?

constexpr Support for Lambda Functions

constexpr support for lambda functions has been a widely discussed topic in the C community. Although lambdas are currently not allowed in constant expressions according to [expr.const]/(2.6), N4487, which is included in the working draft N4582, proposes to remove this restriction.

Proposed lambda-related changes:

  • Allow lambdas in constant expressions.
  • Consider a closure type as a literal type if all of its data members are literal types.
  • If the constexpr specifier is omitted within the lambda declarator, the generated function call operator is considered constexpr if it meets the requirements of a constexpr function.

Example:

The following example will be valid once N4487 is accepted:

<code class="c++">struct Test
{
  static const int value = []() constexpr { return 0; } ();
};</code>

Workaround:

As a workaround before constexpr support is officially added, you can use a function template instead of a lambda:

<code class="c++">struct Test
{
  template <typename>
  static const int value = 0;
};</code>

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

Statement:
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