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.

有帮助吗?

解决方案

You can do it by creating a friend function that returns the lambda function. It inherits the friend access:

struct A {
  friend std::function<void(A&, int)> f();

  private:
    int i;
    void test() {std::cout << "test: " << i << "\n";}
};

std::function<void(A&, int)> f() {
  return [] (A &a, int i) {a.i = i; a.test(); };
}

int main() {
    A a;
    f()(a, 13);

    return 0;
}

其他提示

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:

#include <iostream>
using namespace std;

class A {
  int a;
public:
    A(int _a) : a(_a) {}
    friend int foo(A*); // Declare foo(A*) a friend of A
};

int foo(A* aa) {
    auto function = [](A* a) {
        return a->a;    // Now foo(A*) can access A::a, which is private
    };
    return function(aa);
}

int main() {
    A a(123);
    cout << foo(&a) << endl;
    return 0;
}

Here is a running demo on ideone.

using std::function takes extra resource, so I recomendet using friend/or method function to access private member (friend function implicit inlined):

class A{
    int a;

    friend int access_member(A*a){ return a->a;}
};

-----------------------------------------
auto function = [](A*a){   return access_member(a); }

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top