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

Can Lambda Functions Be Used in `constexpr` Contexts?

DDD
Release: 2024-10-31 00:30:29
Original
1045 people have browsed it

 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>
Copy after login

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>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template