Ways to detect whether a C++ virtual function has been redefined in a derived class

前端 未结 9 1448
不知归路
不知归路 2020-12-01 14:10

In brief: From a C++ base-class pointer which points to an instance of a derived class, how can one determine at run-time whether a non-pure virtual functio

9条回答
  •  青春惊慌失措
    2020-12-01 14:18

    Perhaps this helps. It alone doesn't answer your original question, but you can augment your base class (here, Foo) to use a certain interface if it is supplied or use a default method otherwise.

    #include 
    
    struct X {
        virtual void x () = 0;
    };
    
    struct Y {
        virtual void y () = 0;
    };
    
    
    struct Foo {
        virtual ~ Foo () {}
    
        bool does_x () {
            return NULL != dynamic_cast  (this);
        }
    
        bool does_y () {
            return NULL != dynamic_cast  (this);
        }
    
        void do_x () {
            dynamic_cast  (*this) .x ();
        }
    
        void do_y () {
            dynamic_cast  (*this) .y ();
        }
    };
    
    struct foo_x : public Foo, public X {
        void x () {
            std :: cout << __PRETTY_FUNCTION__ << std :: endl;
        }
    };
    
    
    struct foo_y : public Foo, public Y {
        void y () {
            std :: cout << __PRETTY_FUNCTION__ << std :: endl;
        }
    };
    
    struct foo_xy : public Foo, public X, public Y {
        void x () {
            std :: cout << __PRETTY_FUNCTION__ << std :: endl;
        }
    
        void y () {
            std :: cout << __PRETTY_FUNCTION__ << std :: endl;
        }
    };
    
    void test (Foo & f)
    {
        std :: cout << &f << " "
            << "{"
            << "X:" << f .does_x () << ", "
            << "Y:" << f .does_y ()
            << "}\n";
    
        if (f .does_x ())
            f .do_x ();
    
        if (f .does_y ())
            f .do_y ();
    }
    
    int main ()
    {
        foo_x x;
        foo_y y;
        foo_xy xy;
        test (x);
        test (y);
        test (xy);
    }
    

提交回复
热议问题