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
  • 23,109
  • 5
  • 38
  • 74
xmllmx
  • 37,882
  • 21
  • 139
  • 300

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
  • 163,662
  • 15
  • 289
  • 382