Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constexpr lambda by default?

According to n4487 and other c++17 references, there will be new lambda function specifier - constexpr , which if present "explicitly specifies that the function call operator is a constexpr function.". I understand the motivation about constant expressions in lambdas. What is interesting for me is point 4 of proposal which states:

4) If the constexpr specifier is omitted within the lambda-declarator, the function call operator (or template) is constexpr if it would satisfy the requirements of a constexpr function.

This leads me to two questions:

  1. Why do we need constexpr specifier? Looks like that whether the lambda call operator will be constexpr or not depends only on the fact will it "satisfy the requirements of a constexpr function", but not from constexpr specifier presence.
  2. If it is acceptable to have constexpr lambda by default, why isn't it proposed for other types of functions as well - for example global functions? What will be the impact if compiler starts to treat all functions which cover requirements as constexpr?
like image 203
Aahzbg Avatar asked Aug 30 '16 06:08

Aahzbg


People also ask

Can 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.

Is constexpr guaranteed?

Quick A: constexpr guarantees compile-time evaluation is possible if operating on a compile-time value, and that compile-time evaluation will happen if a compile-time result is needed.

Is constexpr always evaluated at compile time?

A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.

Should I use constexpr everywhere?

Yes. I believe putting such const ness is always a good practice wherever you can. For example in your class if a given method is not modifying any member then you always tend to put a const keyword in the end.


1 Answers

  1. The constexpr qualifier makes it a compile error for the lambda to violate the requirements of constexpr functions. You use it when you explicitly need the lambda to be constexpr, so that you don't accidentally make it not constexpr.

  2. Asked and answered.

like image 105
Nicol Bolas Avatar answered Oct 04 '22 03:10

Nicol Bolas