令我惊讶的是下面的代码打印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的流操作,这样就选择了重载,就会发生隐式转换。看:如何用cout打印函数指针? https://stackoverflow.com/questions/2064692/how-to-print-function-pointers-with-cout.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)