【发布时间】:2013-01-08 16:16:32
【问题描述】:
我想bind() 到派生类中我的基类版本的函数。该功能在底座中标记为受保护。当我这样做时,代码在 Clang (Apple LLVM Compiler 4.1) 中顺利编译,但在 g++ 4.7.2 和 Visual Studio 2010 中都出现错误。错误类似于:“'Base::foo': cannot访问受保护的成员。”
这意味着引用的上下文实际上在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 这是“合法但不受欢迎”的“不受欢迎”部分。
标签: c++ c++11 protected derived-class stdbind