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

标签 c++ c++11 protected derived-class stdbind

我想从派生类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/34021084/

相关文章:

c++ - 如何在正则表达式中匹配 "["和 "]"?

java - Java中 protected 和包私有(private)的访问修饰符之间的区别?

c++ - 我对在 C++ 中将指针作为参数传递有什么误解?

c++ - 我正在尝试获取数组中的随机元素,为什么我的简单代码不起作用?

c++ - 在 QBoxLayout 中添加新的子窗口小部件期间,Qt 视口(viewport)窗口小部件不会扩展

c++ - 在 C++11 中使用的前向声明

c++ - 我将如何为 C++ 项目使用 Python 类定义

c++ - 二叉搜索树的智能指针深度优先搜索

java - 抽象类中的 protected 数据

C++ 继承和访问 protected 基类成员 : is doing it Java-style a bad idea?