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

C++LambdaConstantsC++11

C++ Problem Overview


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

C++ Solutions


Solution 1 - C++

Use mutable.


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

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

Solution 2 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZacView Question on Stackoverflow
Solution 1 - C++Edward StrangeView Answer on Stackoverflow
Solution 2 - C++VladView Answer on Stackoverflow