为什么这个 lambda 可以流式传输?

Why is this lambda streamable?

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

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

有人可以解释一下吗?

它正在转换为函数指针,然后通过它转换为布尔值:

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

打印相同的内容和相同的警告;我碰巧将 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;

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

补充一下我的回答:void* 存在流过载。但是,函数指针与数据指针不同,不能隐式转换为 void*。函数指针唯一的隐式转换是boolean,当然还有bool的流操作,所以选择了重载,就发生了隐式转换。参见:How to print function pointers with cout?.