为什么这个lambda可以流动?

SU3*_*SU3 11 c++ lambda cout c++11

令我惊讶的是,以下代码打印出来1.

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

有人可以解释一下吗?

Nir*_*man 12

它转换为函数指针,然后通过它转换为bool:

void foo ();
std::cout << &foo << std::endl;
Run Code Online (Sandbox Code Playgroud)

打印相同的东西,同样的警告; 我碰巧用gcc设置为17标准编译,我看到:

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;
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,您会看到相同的警告.

添加一点我的答案:有一个流重载void*.但是,与指向数据的指针不同,函数指针不能隐式转换为void*.函数指针的唯一隐式转换是boolean,当然还有bool的流操作,因此选择了重载并发生隐式转换.请参阅:如何使用cout打印函数指针?.