我想bind()
從派生類的基類的函數版本。該功能在底座中被標記爲受保護。當我這樣做的時候,代碼在Clang(Apple LLVM Compiler 4.1)中編譯得很愉快,但是在g ++ 4.7.2和Visual Studio 2010中都出現了一個錯誤。錯誤是:''Base :: foo':can not訪問受保護的成員「。std :: bind() - 來自派生類的成員函數的基本保護成員函數
含義是引用的上下文實際上在bind()
之內,當然這個函數被視爲受保護的。但不應該bind()
繼承調用函數的上下文 - 在這種情況下,Derived::foo()
- 因此看到基本方法可訪問?
下面的程序說明了這個問題。
struct Base
{
protected: virtual void foo() {}
};
struct Derived : public Base
{
protected:
virtual void foo() override
{
Base::foo(); // Legal
auto fn = std::bind(&Derived::foo,
std::placeholders::_1); // Legal but unwanted.
fn(this);
auto fn2 = std::bind(&Base::foo,
std::placeholders::_1); // ILLEGAL in G++ 4.7.2 and VS2010.
fn2(this);
}
};
爲什麼行爲上的差異?哪個是對的?解決錯誤的編譯器有哪些解決方法?
「Derived :: foo」本身是故意的,還是僅僅是簡化爲例的結果? – aschepler
@aschepler這是「合法但不需要」的「不需要」部分。 – OldPeculier