How to make the lambda a friend of a class?

后端 未结 3 546
说谎
说谎 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 f();
    
      private:
        int i;
        void test() {std::cout << "test: " << i << "\n";}
    };
    
    std::function f() {
      return [] (A &a, int i) {a.i = i; a.test(); };
    }
    
    int main() {
        A a;
        f()(a, 13);
    
        return 0;
    }
    

提交回复
热议问题