why can't I cast a pointer to Derived class member function to the same but of class Base?

后端 未结 4 644
半阙折子戏
半阙折子戏 2020-12-06 19:48

To me it looks perfectly safe to cast a void(Derived::*)() to a void(Base::*)(), like in this code:

#include 
#incl         


        
4条回答
  •  -上瘾入骨i
    2020-12-06 20:19

    You need to use a std::function. This can be any member of any class, a lambda, a free function, a function object, whatever you need, which is super convenient.

    #include 
    #include 
    using namespace std;
    struct Base{
        std::function any_method;
        void call_it(){
            any_method();
        }
    };
    struct Derived: public Base{
        void a_method(){
            cout<<"method!"<a_method(); };
        a.call_it();
    }
    

    Here you can see that the actual implementation of any_method is totally abstracted from struct Base, and I can supply a function object that does anything, at all- including conveniently calling a Derived method.

提交回复
热议问题