c ++函数成员指针 [英] c++ Function member pointer
问题描述
我已经阅读了几个帖子,但是似乎找不到我正在寻找的示例代码,如果任何人可以给我一些帮助,我会非常感激它。
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.
在我的标题中有:
void addEvent(void (*func)(Pack *));
void triggerEvents(Pack * );
std::list<void(*)(Pack *)> eventList;
和cpp文件
void DNetwork::addEvent(void (*func)(Pack *)){
eventList.push_back(func);
}
void DNetwork::triggerEvents(Pack * pack){
for (std::list<void (*)( Pack *)>::iterator it = eventList.begin(); it != eventList.end() ;it++ ){
(*it)(pack);
}
}
这对自由功能很好,添加成员函数到此列表我得到一个错误。
This works fine with free functions, but when i try to add a member function to this list i get an error. Does anyone know how to store a member function (from random class objects) inside a pointer?
推荐答案
对于成员函数,你需要一个成员函数绑定。成员函数是具有其类的隐式参数的正常函数。所以你需要一个binder。如果你使用c ++ 11,你可以使用std :: bind和std :: function,也可以对非c ++ 11代码使用boost :: bind和boost :: function。
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);
}
}
现在如果我有类A, code> doA(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 ) );
或者更好的方法是使用Boost.Signal或者使用发布者/子模式
Or even better you can use Boost.Signal or you can use the Publisher/Subcriber Pattern
编辑
As @DavidRodríguez-dribeas建议:bind不应该使用& pack参数,因为成员函数的参数在triggerEvents中的调用位置提供。正确的方法是:
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 );
这篇关于c ++函数成员指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!