Can you cache a virtual function lookup in C++?

前端 未结 9 1177
故里飘歌
故里飘歌 2021-01-31 15:39

Say I have a virtual function call foo() on an abstract base class pointer, mypointer->foo(). When my app starts up, based on the contents of a file, it chooses to instantiate a

9条回答
  •  误落风尘
    2021-01-31 16:28

    You can't use a method pointer because pointers to member functions aren't considered covariant return types. See the example below:

    #include 
    
    struct base;
    struct der;
    
    typedef void(base::*pt2base)();
    typedef void(der::*pt2der)();
    
    struct base {
        virtual pt2base method() = 0;
        virtual void testmethod() = 0;
        virtual ~base() {}
    };
    
    struct der : base {
        void testmethod() {
            std::cout << "Hello from der" << std::endl;
        }
        pt2der method() { **// this is invalid because pt2der isn't a covariant of pt2base**
            return &der::testmethod;
        }
    };
    

    The other option would be to have the method declared pt2base method() but then the return would be invalid because der::testmethod is not of type pt2base.

    Also even if you had a method that received a ptr or reference to the base type you would have to dynamically cast it to the derived type in that method to do anything particularly polymorphic which adds back in the cost we're trying to save.

提交回复
热议问题