Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this lambda streamable?

To my surprise the following code prints 1.

std::cout << [](const char* arg){ return arg[0]=='s'; } << std::endl;

Can someone explain this, please?

like image 514
SU3 Avatar asked Jul 10 '17 02:07

SU3


1 Answers

It's converting to a function pointer, and then through that to a bool:

void foo ();
std::cout << &foo << std::endl;

Prints the same thing, and the same warnings; I happened to compile with gcc set to 17 standard and I saw:

main.cpp:6:56: warning: the address of 'static constexpr bool main()::<lambda(const char*)>::_FUN(const char*)' will never be NULL [-Waddress]
  std::cout << [](const char* arg){ return arg[0]=='s'; } << std::endl;

With the code above you see the same warning.

To add on a bit to my answer: there is a stream overload for void*. However, function pointers, unlike pointers to data, cannot implicitly convert to void*. The only implicit conversion for function pointers is boolean, and of course there is a stream operation for bool, so that overload is selected and that implicit conversion occurs. See: How to print function pointers with cout?.

like image 195
Nir Friedman Avatar answered Oct 23 '22 13:10

Nir Friedman