std::bind()-ing a base protected member function from a derived class's member function

前端 未结 2 1100
感情败类
感情败类 2021-01-17 17:07

I want to bind() to my base class\'s version of a function from the derived class. The function is marked protected in the base. When I do so, the code compiles

2条回答
  •  太阳男子
    2021-01-17 17:59

    This has nothing to do with bind. Because of the piece of the Standard @rhalbersma already quoted, the expression &Base::foo is illegal in a non-friended member of Derived, in every context.

    But if your intent was to do something equivalent to calling Base::foo();, you have a bigger issue: pointers to member functions always invoke a virtual override.

    #include 
    
    class B {
    public:
        virtual void f() { std::cout << "B::f" << std::endl; }
    };
    
    class D : public B {
    public:
        virtual void f() { std::cout << "D::f" << std::endl; }
    };
    
    int main() {
        D d;
        d.B::f();   // Prints B::f
    
        void (B::*ptr)() = &B::f;
        (d.*ptr)(); // Prints D::f!
    }
    

提交回复
热议问题