How to make the lambda a friend of a class?

2019-04-06 06:53发布

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.

3条回答
孤傲高冷的网名
2楼-- · 2019-04-06 07:32

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

查看更多
女痞
3楼-- · 2019-04-06 07:47

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.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-04-06 07:58

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;
}
查看更多
登录 后发表回答