Why would one use function pointers to member method in C++?

前端 未结 10 2157
情书的邮戳
情书的邮戳 2021-02-10 23:48

A lot of C++ books and tutorials explain how to do this, but I haven\'t seen one that gives a convincing reason to choose to do this.

I understand very well why functio

10条回答
  •  感动是毒
    2021-02-11 00:16

    I used a function pointer to a member function in a scenario where I had to provide a function pointer to a callback with a predefined parameter list (so I couldn't pass arbitrary parameters) to some 3rd-party API object.

    I could not implement the callback in the global namespace because it was supposed to handle incoming events based on state of the object which made use of the 3rd party API which had triggered the callback.

    So I wanted the implementation of the callback to be part of the class which made use of the 3rd-party object. What I did is, I declared a public and static member function in the class I wanted to implement the callback in and passed a pointer to it to the API object (the static keyword sparing me the this pointer trouble).

    The this pointer of my object would then be passed as part of the Refcon for the callback (which luckily contained a general purpose void*). The implementation of the dummy then used the passed pointer to invoke the actual, and private, implementation of the callback contained in the class = ).

    It looked something like this:

    public:
        void SomeClass::DummyCallback( void* pRefCon ) [ static ]
        {
            reinterpret_cast(pRefCon)->Callback();
        }
    private:
        void class SomeClass::Callback() [ static ]
        {
            // some code ...
        }
    

提交回复
热议问题