#include <type_traits>
int main()
{
auto f = [] {};
static_assert(std::is_same_v<decltype(!f), bool>); // ok
f.operator bool(); // error: ‘struct main()::<lambda()>’
// has no member named ‘operator bool’
}
Does C++ guarantee the lambda unnamed class always has an operator bool()
defined?
No, lambdas doesn't have operator bool()
.
!f
works because lambdas without captures could convert to function pointer (which have a conversion operator for it), and then could convert to bool
, with the value true
since the pointer is not null.
On the other hand,
int x;
auto f = [x] {};
!f; // not work; lambdas with captures can't convert to function pointer (and bool)