lambda returns '1' all time

亡梦爱人 提交于 2020-01-02 04:45:11

问题


Have code like this

#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;
}

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


回答1:


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

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

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

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

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




回答2:


What you say:

cout<<[](){ return 0;};

What you want to say:

cout<<[](){ return 0;}();

See the bracket?




回答3:


What if you did this:

#include <iostream>
using namespace std;
void foo()
{
}
int main() 
{ 
  cout<<foo;
  return 0;
}

You're not calling the method, but attempting to print its address. The overload operator <<(bool) for cout is chosen, thus for any valid function you attempt to print, you get a 1.

To actually, call the function (or lambadas), add ().



来源:https://stackoverflow.com/questions/28273891/lambda-returns-1-all-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!