lambda返回“1”所有时间 [英] lambda returns '1' all time

查看:151
本文介绍了lambda返回“1”所有时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有这样的代码

#include <iostream>
using namespace std;
int main() 
{ 
  cout<<[](){ return 0;};
  cout<<[](){ return 3.2;};
  cout<<[](){ return true;};
  cout<<[](){ return false;};
  cout<<[](){ return "Hello world!";};
  cout<<[]()->int{ return 0;};
  cout<<[]()->double{ return 3.2;};
  cout<<[]()->bool{ return true;};
  cout<<[]()->bool{ return false;};
  cout<<[]()->const char*{ return "Hello world!";};
  return 0;
}

使用 gcc version 4.8.2 ,我的输出只有 1111111111
为什么只有1?

Compile it with gcc version 4.8.2 and my output is only 1111111111. Why only "1"?

推荐答案

当lambda表达式没有捕获,它可以隐式转换为函数指针。

When a lambda expression has no capture, it is implicitly convertible to a function pointer.

函数指针又可隐式转换为 bool ,产生

A function pointer, in turn, is implicitly convertible to bool, yielding true if the pointer is not null, which gets printed.

如果 cout<< std :: boolalpha ,然后您将看到 truetruetrue .. .. 改为打印

If you cout << std::boolalpha before your outputs, you'll see truetruetrue.... printed instead.

如果你在lambda中捕获了一些东西,那么它不再可以转换为函数指针,和您会收到编译错误

If you capture something in your lambda, then it is no longer convertible to a function pointer, and you'd get a compiler error.

如果你想打印通过调用lambda返回的结果,那么你需要(),正如其他人所指出的那样。

If you want to print the result returned by calling the lambda, then you need (), as others have pointed out.

这篇关于lambda返回“1”所有时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆