Having a class like this:
class A {
public:
bool hasGrandChild() const;
private:
bool hasChild() const;
vector<A> children_;
};
Why is it not possible to use a private method hasChild() in a lambda expression defined in the method hasGrandChild() like this?
bool A::hasGrandChild() const {
return any_of(children_.begin(), children_.end(), [](A const &a) {
return a.hasChild();
});
}
Compiler issues an error that the method hasChild() is private within the context. Is there any workaround?
Edit:
It seems that the code as I posted it originally works. I thought that it is equivalent, but the code that does not work on GCC is more like this:
#include <vector>
#include <algorithm>
class Foo;
class BaseA {
protected:
bool hasChild() const { return !children_.empty(); }
std::vector<Foo> children_;
};
class BaseB {
protected:
bool hasChild() const { return false; }
};
class Foo : public BaseA, public BaseB {
public:
bool hasGrandChild() const {
return std::any_of(children_.begin(), children_.end(), [](Foo const &foo) {
return foo.BaseA::hasChild();
});
}
};
int main()
{
Foo foo;
foo.hasGrandChild();
return 0;
}
Seems that there is a problem with fully qualified names as this does not work, but this works.
It seems to be just a GCC bug in a special case when the lambda tries to access a protected member from parent class using fully qualified name. This does not work:
, but this works:
According to C++11, 5.1.2/3:
And then C++11, 11.7/1:
So the mentioned function-local lambda should have the same access rights as any other member of the class. Therefore it should be able to call a protected method from a parent class.