Boost::Bind and virtual function overloads: why do they work?

后端 未结 2 1333
挽巷
挽巷 2021-01-04 11:44

I wrote some code and got scared that it will not work - so I wrote a prototype:

#include 
#include 
#include         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-04 12:15

    A pointer to a virtual method does a virtual function lookup when called.

    #include 
    #include 
    
    struct base {
      virtual void foo() { std::cout << "base\n"; }
      virtual ~base() {}
    };
    
    struct derived:base {
      void foo() override final { std::cout << "derived\n"; }
    };
    
    int main() {
      void (base::*mem_ptr)() = &base::foo;
      std::unique_ptr d( new derived() );
      base* b = d.get();
      (b->*mem_ptr)();
    }
    

    so, it "just works". The member function pointer (this->*&base::foo)() is not the same as a fully qualified function call this->base::foo(). The first is a way to store the foo part of calling this->foo(), the second is a way to skip virtual method lookup and directly call base::foo.

提交回复
热议问题