C++0x lambda capture by value always const?

匿名 (未验证) 提交于 2019-12-03 02:56:01

问题:

Is there any way to capture by value, and make the captured value non-const? I have a library functor that I would like to capture & call a method that is non-const but should be.

The following doesn't compile but making foo::operator() const fixes it.

struct foo {   bool operator () ( const bool & a )   {     return a;   } };   int _tmain(int argc, _TCHAR* argv[]) {   foo afoo;    auto bar = [=] () -> bool     {       afoo(true);     };    return 0; } 

回答1:

Use mutable.

 auto bar = [=] () mutable -> bool .... 

Without mutable you are declaring the operator () of the lambda object const.



回答2:

There is alternative way to using mutable (solution proposed by Crazy Eddie).

With [=] your block captures all objects by values. You can use [&] to capture all objects by reference:

auto bar = [&] () -> bool 

Or you can capture by reference only certain object [=, &afoo]:

auto bar = [=, &afoo] () -> bool 

Refer to this page for fore details (Explanation section): http://en.cppreference.com/w/cpp/language/lambda



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