gpt4 book ai didi

c++ - std::bind() - 从派生类的成员函数中获取基保护成员函数

转载 作者:可可西里 更新时间:2023-11-01 15:03:25 27 4
gpt4 key购买 nike

我想从派生类bind() 到我的基类版本的函数。该功能在基础中被标记为 protected 。当我这样做时,代码在 Clang(Apple LLVM 编译器 4.1)中编译愉快,但在 g++ 4.7.2 和 Visual Studio 2010 中都出现错误。错误如下:“'Base::foo':不能访问 protected 成员。”

这意味着引用的上下文实际上在 bind() 中,当然函数在其中被视为 protected 。但是 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 );
}
};

为什么会出现行为差异?哪个是对的?出现错误的编译器有什么解决方法?

最佳答案

答案:参见boost::bind with protected members & context其中引用了标准的这一部分

An additional access check beyond those described earlier in clause 11 is applied when a non-static data member or nonstatic member function is a protected member of its naming class (11.2)105) As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C. If the access is to form a pointer to member (5.3.1), the nested-name-specifier shall name C or a class derived from C. All other accesses involve a (possibly implicit) object expression (5.2.5). In this case, the class of the object expression shall be C or a class derived from C.

解决方法:将 foo 设为 public 成员函数

#include <functional>

struct Base
{
public: virtual void foo() {}
};

关于c++ - std::bind() - 从派生类的成员函数中获取基保护成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14509291/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com