Why is it not possible to use private method in a lambda?

后端 未结 5 1364
醉酒成梦
醉酒成梦 2020-12-10 11:23

Having a class like this:

class A {
public:
    bool hasGrandChild() const;

private:
    bool hasChild() const;
    vector children_;
};

5条回答
  •  隐瞒了意图╮
    2020-12-10 11:34

    You can capture this explicitly and make it a "member lambda" that has access to private members.

    For example, consider the following sample:

    #include 
    class A {
    private:
        void f() { std::cout << "Private"; }
    public:
        void g() { 
            [this] { 
                f(); 
                // doesn't need qualification 
            }(); 
        }
    };
    class B {
    private:
        void f() { std::cout << "Private"; }
    public:
        void g() { [] { f(); }(); } // compiler error
    };
    int main() {
        A a;
        a.g();
    }
    

提交回复
热议问题