How to make the lambda a friend of a class?

后端 未结 3 528
说谎
说谎 2020-12-17 17:05

Let\'s say, I have a class:

class A {
  int a;
};

And I have a lambda:

auto function = [](A* a) {
  a->a;  // <== giv         


        
相关标签:
3条回答
  • 2020-12-17 17:40

    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;
    }
    
    0 讨论(0)
  • 2020-12-17 17:45

    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

    0 讨论(0)
  • 2020-12-17 17:58

    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.

    0 讨论(0)
提交回复
热议问题