c++ Function member pointer

前端 未结 4 1936
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 09:43

I have read several posts about this, but can\'t seem to find exactly what i am looking for with example code if anyone could give me some help i would highly appreciate it.

4条回答
  •  长情又很酷
    2021-01-29 09:52

    For member function you need a bind. A member function is a "normal function" that has an implicit parameter of its class. So you need a binder. If you use c++11 you can use std::bind and std::function or you can use boost::bind and boost::function for non c++11 code.

    typedef std::function< void ( Pack* ) > MyFunction;
    void addEvent( MyFunction f );
    void triggerEvents( Pack* );
    std::list< MyFunction > eventList;
    
    void DNetwork::addEvent( MyFunction f )
    {
        eventList.push_back( f );
    }
    
    void DNetwork::triggerEvents( Pack *pack )
    {
        for ( auto it = eventList.begin(); it != eventList.end(); it++ )
        {
            (*it)(pack);
        } 
    }
    

    Now if I have the class A with the method doA( Pack* ) I will write:

    A a;
    Pack pack;
    DNetwork d;
    d.addEvent( std::bind( &A::doA, &a, &pack ) );
    

    Or even better you can use Boost.Signal or you can use the Publisher/Subcriber Pattern

    Edit As @DavidRodríguez-dribeas suggest: The bind should not take the &pack argument, as the argument to the member function is provided at the place of call in triggerEvents. The correct way is:

    A a;
    Pack pack;
    DNetwork d;
    d.addEvent( std::bind( &A::doA, &a, std::placeholders::_1 ) );
    d.triggerEvents( &pack );
    

提交回复
热议问题