有這樣一類:爲什麼在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