C++ 是否保证 lambda 未命名类始终定义“operator bool()”?

xml*_*lmx 0 c++ lambda standards operator-overloading c++14

#include <type_traits>\n\nint main()\n{\n    auto f = [] {};\n    static_assert(std::is_same_v<decltype(!f), bool>); // ok\n\n    f.operator bool(); // error: \xe2\x80\x98struct main()::<lambda()>\xe2\x80\x99 \n                       // has no member named \xe2\x80\x98operator bool\xe2\x80\x99\n}\n
Run Code Online (Sandbox Code Playgroud)\n

C++ 是否保证 lambda 未命名类始终具有已operator bool()定义的?

\n

son*_*yao 5

不,lambda没有operator bool().

!f之所以有效,是因为没有捕获的 lambda 可以转换为函数指针(函数指针有一个转换运算符),然后可以转换为bool, true,因为指针不为空。

另一方面,

int x;
auto f = [x] {};
!f; // not work; lambdas with captures can't convert to function pointer (and bool)
Run Code Online (Sandbox Code Playgroud)

  • 重复/sf/ask/2920469261/ (2认同)