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

前端 未结 10 2155
情书的邮戳
情书的邮戳 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:13

    The single most important use of member pointers is creating functors. The good news is that you hardly even need to use it directly, as it is already solved in libraries as boost::bind, but you do have to pass the pointers to those libs.

    class Processor
    {
    public:
       void operation( int value );
       void another_operation( int value );
    };
    int main()
    {
       Processor tc;
       boost::thread thr1( boost::bind( &Processor::operation, &tc, 100 ) );
       boost::thread thr2( boost::bind( &Processor::another_operation, &tc, 5 ) );
       thr1.join();
       thr2.join();
    }
    

    You can see the simplicity of creating a thread that executes a given operation on a given instance of a class.

    The simple handmade approach to the problem above would be on the line of creating a functor yourself:

    class functor1
    {
    public:
        functor1( Processor& o, int v ) : o_(o), v_(v) {}
        void operator()() {
            o_.operation( v_ ); // [1]
        }
    private:
        Processor& o_;
        int v_;
    };
    

    and create a different one for each member function you wish to call. Note that the functor is exactly the same for operation and for another_operation, but the call in [1] would have to be replicated in both functors. Using a member function pointer you can write a simple functor:

    class functor
    {
    public:
       functor( void (*Processor::member)(int), Processor& p, int value )
          : member_( member ), processor_(p), value_( value ) {}
    
       void operator()() {
          p.*member(value_);
       }
    private:
       void (*Processor::member_)(int);
       Processor& processor_;
       int value;
    };
    

    and use it:

    int main() {
       Processor p;
       boost::thread thr1( functor( &Processor::operation, p, 100 ) );
       boost::thread thr2( functor( &Processor::another_operation, p, 5 ) );
       thr1.join();
       thr2.join();
    }
    

    Then again, you don't need to even define that functor as boost::bind does it for you. The upcoming standard will have its own version of bind along the lines of boost's implementation.

    0 讨论(0)
  • 2021-02-11 00:14

    I have some code I'm working on right now where I used them to implement a state machine. The dereferenced member functions implement the states, but since they are all in the class they get to share a certian amount of data that is global to the entire state machine. That would have been tough to accomplish with normal (non-member) function pointers.

    I'm still undecided on if this is a good way to implement a state machine though.

    0 讨论(0)
  • 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<SomeClassT*>(pRefCon)->Callback();
        }
    private:
        void class SomeClass::Callback() [ static ]
        {
            // some code ...
        }
    
    0 讨论(0)
  • 2021-02-11 00:18

    I have used member function pointers parsing a file. Depending on specific strings found in the file the same value was found in a map and the associated function called. This was instead of a large if..else if..else statement comparing strings.

    0 讨论(0)
  • 2021-02-11 00:19

    You asked specifically about member functions, but there are other uses for function pointers as well. The most common reason why I need to use function pointers in C++ is when I want to load a DLL ar runtime using LoadLibrary(). This is in Windows, obviously. In applications that use plugins in the form of optional DLLs, dynamic linking can't be used at application startup since the DLL will often not be present, and using delayload is a pain.

    After loading the library, you have to get a pointer to the functions you want to use.

    0 讨论(0)
  • 2021-02-11 00:20

    A pointer to a member function is object-agnostic. You need it if you want to refer to a function by value at run-time (or as a template parameter). It comes into its own when you don't have a single object in mind upon which to call it.

    So if you know the function, but don't know the object AND you wish to pass this knowledge by value, then point-to-member-function is the only prescribed solution. Iraimbilanja's example illustrates this well. It may help you to see my example use of a member variable. The principle is the same.

    0 讨论(0)
提交回复
热议问题