我正在阅读书籍《C++17完全教程》,在第6.1节中讲到了constexpr
lambda,作者给出了两个示例:
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;
};
并表示这两者不同,因为示例1在编译时进行评估,而示例2在编译时进行初始化。
接下来作者提出了以下几点声明,我并不完全理解:
If (only) the lambda is
constexpr
it 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; };
以上语句的确切含义是什么?
显然,在squared2
lambda对象的初始化语句和 lambda表达式本身中,constexpr
关键字出现在示例 3中,但我不理解这与示例 1相比有何优势。
constexpr
,带整数的异常最令人困惑... - Jarod42