functor accessing class members ?

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
binbinhfr
Posts: 78
Joined: May 9th, 2019, 10:57 pm

functor accessing class members ?

Post by binbinhfr » May 16th, 2020, 8:23 pm

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 ?

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: functor accessing class members ?

Post by albinopapa » May 16th, 2020, 9:07 pm

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(); 
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: functor accessing class members ?

Post by albinopapa » May 16th, 2020, 9:10 pm

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.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

binbinhfr
Posts: 78
Joined: May 9th, 2019, 10:57 pm

Re: functor accessing class members ?

Post by binbinhfr » May 17th, 2020, 12:36 pm

Ok thanks man, I did not read enough about the [] part !!!

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: functor accessing class members ?

Post by albinopapa » May 17th, 2020, 5:01 pm

Lambdas confused the crap out of me when they first came to C++. I couldn't figure out the capture part either.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

Post Reply