0
#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?

Evg
  • 25,259
  • 5
  • 41
  • 83
xmllmx
  • 39,765
  • 26
  • 162
  • 323

1 Answers1

5

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)
songyuanyao
  • 169,198
  • 16
  • 310
  • 405