c++ Function member pointer

亡梦爱人 提交于 2019-12-02 13:10:50

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 );

The simple solution is using type erasure on the function/function pointer type, for which the easier way is just using std::function<>:

std::list<std::function<void (Pack*)>;

Then you can initialize the function objects with either a free function or a member function (by means of std::bind to bind the member-function with an object on which to call it) or even function objects (types that offer an operator()).

You could do an overload such as:

std::list<void(*)(Pack *)> eventList;
void addEvent(void (*func)(Pack  *));
template<typename T>
void addEvent(void (T::*func)(Pack  *));
namespace Abstraction {
    template<typename T>
    void abstractlyAddEvent( T, std::list<void(*)(Pack *)> *eventList );
}

If I'm understanding your problem you get the error when you try to add a function to the list in addEvent?

If you're adding a pointer to a non-static member function of a class ensure it has the right syntax... for example a function pointer to a a member function in TestClass would look like:

void * (TestClass:: *) ()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!