I was reading book C++17 - The Complete Guide and in the section 6.1 on constexpr lambda the author gives two examples:
auto squared1 = [](auto val) constexpr { // example 1. compile-time lambda calls
return val * val;
};
and
constexpr auto squared2 = [](auto val) { // example 2. compile-time initialization
return val * val;
};
and says that these two are different from each other in the sense that example 1 is evaluated at compile time and example 2 is initialized at compile time.
The author then makes the following statements which I don't understand completely:
If (only) the lambda is
constexprit can be used at compile time, but If the (closure) object initialized by the lambda isconstexpr, the object is initialized when the program starts but the lambda might still be a lambda that can only be used at run time (e.g., using static variables). Therefore, you might consider declaring:constexpr auto squared = [](auto val) constexpr { // example 3 return val * val; };
What does the above statement mean exactly?
It is obvious that the constexpr keyword appears on initialization statement of squared2 lambda object and on the lambda expression itself in example 3 but I don't understand what is the advantage of this over example 1 .