Page 1 of 1

functor accessing class members ?

Posted: May 16th, 2020, 8:23 pm
by binbinhfr
Hi there,

I just discover functors and I'd like to use them as functions into functions, to reduce the scope of these subfunctions, as little local swiss knifes. What I would like to do is something like this :

Code: Select all

class A
{
  void f();
  int x;
}

void A::f()
{
  auto g = []()  
  {
    x *= 2;
  }

  g();
}
he says : "an enclosing-function local variable cannot be referenced in a lambda body unless if it is in capture list"
I cannot figure out what it means, but g cannot access A members ?

Re: functor accessing class members ?

Posted: May 16th, 2020, 9:07 pm
by albinopapa
You have 3+ options.

Capture the 'this' pointer

Code: Select all

 auto g = [this](){ x *= 2; };
Capture all used variables by reference

Code: Select all

auto g = [&](){ x *=2; };
Capture all used variables by value ( ie. make copies )

Code: Select all

auto g = [=](){ return x * 2; }; x = g();
Capture specific variables by reference

Code: Select all

auto g = [&x](){ x *= 2; };
Capture specific variable by value

Code: Select all

auto g = [x](){ return x * 2; }; x = g(); 

Re: functor accessing class members ?

Posted: May 16th, 2020, 9:10 pm
by albinopapa
Btw, the [](){} is called a lambda. While it is a functor, it is more specifically called a lambda. A general functor is an object that can be used as a function like a struct or class with the operator() is overloaded. This is actually what a lambda is, but for clarification when referring to functors that have the declaration of: [](){}; then it's called a lambda or local function object.

Re: functor accessing class members ?

Posted: May 17th, 2020, 12:36 pm
by binbinhfr
Ok thanks man, I did not read enough about the [] part !!!

Re: functor accessing class members ?

Posted: May 17th, 2020, 5:01 pm
by albinopapa
Lambdas confused the crap out of me when they first came to C++. I couldn't figure out the capture part either.