Search code examples
c++lambdaoperator-overloadingc++14standards

Does C++ guarantee the lambda unnamed class always has an "operator bool()" defined?


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


Solution

  • 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)