我想要在派生类中将bind()
绑定到基类版本的函数。该函数在基类中标记为受保护的。当我这样做时,代码可以在Clang(Apple LLVM Compiler 4.1)中编译通过,但在g++ 4.7.2和Visual Studio 2010中会出现错误。错误信息大致为:“'Base::foo' : cannot access protected member.”
这意味着引用的上下文实际上是在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