How to make the lambda a friend of a class?

后端 未结 3 542
说谎
说谎 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: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

提交回复
热议问题