Let's say, I have a class:
class A {
int a;
};
And I have a lambda:
auto function = [](A* a) {
a->a; // <== gives an error in this line.
};
function(new A);
Is there any way to use a private member/method inside a lambda? - It's not necessary to pass the pointer to the lambda - it may be a capture-by or something else.
All reasonable schemes are welcome.
using std::function takes extra resource, so I recomendet using friend/or method function to access private member (friend function implicit inlined):
Live example
EDIT: I personally like std::function, but don't forgot, std::function always takes extra memory resources, and may not inlined , so if you may implement your source without std::function, don't use std::function. See, How is std::function implemented? Also, Lambda to std::function conversion performance
In order to make a lambda a friend, you need to befriend a class or a function where the lambda is defined. Here is a complete example:
Here is a running demo on ideone.
You can do it by creating a friend function that returns the lambda function. It inherits the friend access: