Why is lambda converted to bool whose value is true?

#include <iostream> void IsTrue(const bool value) { if (value) { std::cout << "value is True!\n"; } } int main() { IsTrue([]() { ; /* some lambda */ }); return 0; } 

Output:

 value is True! 

Why is lambda evaluated to true on GCC and Clang? MSVC cannot build this (cannot convert lambda to bool).

Is this a compiler error? Or what standard item allows this?

+46
c ++ language-lawyer lambda boolean
Jan 18 '17 at 13:41 on
source share
1 answer

The C ++ 14 standard (ยง5.1.2) states:

The closure type for a non-generic lambda expression without lambda-capture has a public non-virtual implicit conversion const for a function pointer with a C ++ binding (7.5) with the same parameters and return types as the closure types of the function call statement. The value returned by this conversion function must be the address of a function that, when called, has the same effect as calling the closure function call statement.

Since the function pointer is implicitly converted to bool , you get the result that you showed. This is completely legal.

MSVC does not compile this because this conversion operator is overloaded with various calling conventions ( __stdcall , __cdecl , etc.). When compiling for x64 all these calling conventions are not used, so there is only one conversion statement, and it compiles fine.

+44
Jan 18 '17 at 13:56 on
source share



All Articles