有这样一类:为什么在lambda中不能使用私有方法?
class A {
public:
bool hasGrandChild() const;
private:
bool hasChild() const;
vector<A> children_;
};
为什么不可能在方法hasGrandChild()
这样定义的lambda表达式使用的私有方法hasChild()
?
bool A::hasGrandChild() const {
return any_of(children_.begin(), children_.end(), [](A const &a) {
return a.hasChild();
});
}
编译器将发出错误的方法hasChild()
是范围内私人。有什么解决方法吗?
编辑: 看来,我发布它的代码原本的作品。我认为这是相当的,但does not work on GCC更多这样的代码:
#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;
}
似乎有是完全合格的名称作为this does not work,但this works一个问题。
闭合类型没有关系到你的类'A',所以自然就不能访问'A'的非公共成员。它也不可能,因为它的名字是不可知的,所以你甚至不能把它变成一个“朋友”。 – 2012-08-13 12:09:23
只是我还是在gcc上做这个工作? http://ideone.com/333qw – pmr 2012-08-13 12:15:30
@pmr:是的,它似乎可以在较老的GCC中工作,但不适用于较新的GCC。 – 2012-08-13 12:28:24