Home > Back-end >  Can a C lambda member function access member variables?
Can a C lambda member function access member variables?

Time:08-16

I am looking for a way for a lambda member function to access member variables. For example:

Given a simple class:

#include <functional>

class MyClass {
public:
  MyClass(function<void()> myFunc);
  int myData = 555;
}

And then when instantiating I can access a class member like so:

MyClass a([](){ std::cout << a.myData; });

But I need to change how I access the data every time I use this e.g.:

MyClass b([](){ std::cout << b.myData; });

Ideally I could capture the member and use it like so:

MyClass a([myData](){ std::cout << myData; });

Thank you!

CodePudding user response:

How about:

struct MyClass {
  MyClass(function<void(int&)> func);
};

And you call it with the member variable as the argument. Or, if you need to access many fields, you may change it to function<void(MyClass&)> and call it with *this as the argument.

CodePudding user response:

I suppose you could define your constructor like this:

MyClass(function<void(MyClass*)> myFunc) {
   myFunc(this);
}

You don't necessarily have to invoke myFunc in your constructor, you could stash it as a member variable.

Then define something like this:

auto fn = [](MyClass* ptr) {
    cout << ptr->myData;
}

So you can invoke constructors like this:

MyClass b(fn);
  • Related