C++: Pointer to monomorphic version of virtual member function?

前端 未结 3 1946
悲&欢浪女
悲&欢浪女 2020-12-05 02:55

In C++, it\'s possible to get a pointer to a (non-static) member function of a class, and then later invoke it on an object. If the function was virtual, the call is dispatc

3条回答
  •  误落风尘
    2020-12-05 03:04

    To elaborate with a code example for a wrapper function (and despite the fact the OP wanted to avoid this method!) as in many cases this is the pragmatically preferable solution:

    #include 
    using std::cout; using std::endl;
    
    struct Foo
    {
        virtual void foo() { cout << 1 << endl; }
    };
    
    struct Foo2: public Foo
    {
        virtual void foo() { cout << 2 << endl; }
    };
    
    void monomorphicFooFoo( Foo * f ) { f->Foo::foo(); }
    
    int main()
    {
        Foo *foo = new Foo2;
    
        void (*baseFoo)( Foo * ) = &monomorphicFooFoo;
        baseFoo( foo ); // Prints 1
    }
    

提交回复
热议问题