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

后端 未结 5 1371
醉酒成梦
醉酒成梦 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:49

    The standard (C++11, §5.1.2/3) states that

    The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed non-union class type — called the closure type.

    Since it's a unique class type that is not a friend of A, it doesn't have access to A's private members.

    What the compiler does here is create a class type that has appropriate members to store any captured variables, an appropriate operator() etc -- which is exactly what you would write yourself if you wanted to emulate lambdas in C++03. This type would certainly not have access to private members, which might make it easier to visualize why the limitation exists and why there is no workaround.

    Update regarding possible workarounds:

    It would be better to say "there are no workarounds using a lambda", because in general workarounds do exist although they require that you forgo the convenient lambda syntax. For example, you could:

    1. Write a local class type that explicitly captures this along with any other locals it requires (inspired by Björn Pollex's comment below).
    2. Write a private method instead of a lambda and pass that as the callback (e.g. using std::bind for convenience). If you want to capture locals in addition to this you can use more std::bind at the call site to do so.

提交回复
热议问题