如果我是你,我不会使用函数指针来完成这项任务。将此选项留给大师;)
在 Boost 中有一个漂亮的库,叫做信号。它让您的生活更轻松!这是一个使用示例:
#include <iostream>
#include <boost/bind.hpp>
#include <boost/signal.hpp>
using namespace std;
using namespace boost;
struct A
{ void A_action() { cout << "A::A_action();" << endl; } };
struct B
{ void B_action() { cout << "B::B_action();" << endl; } };
struct C
{ void C_action() { cout << "C::C_action();" << endl; } };
struct X
{
// Put all the functions you want to notify!
signal<void()> list_of_actions;
void do_something()
{
std::cout << "Hello I am X!" << endl;
list_of_actions(); // send notifications to all functions in the list!
}
};
int main()
{
X x;
A a;
B b;
C c;
x.list_of_actions.connect(bind(&A::A_action, a));
x.list_of_actions.connect(bind(&B::B_action, b));
x.list_of_actions.connect(bind(&C::C_action, c));
x.do_something();
}
这将打印:
Hello I am X!
A::A_action();
B::B_action();
C::C_action();
下面是它的工作原理。
首先,您声明持有代表的地方:
signal<void()> list_of_actions;
然后,您将它“连接”到您想要调用的任何函数/函子/可调用事物组。
x.list_of_actions.connect(bind(&A::A_action, a));
x.list_of_actions.connect(bind(&B::B_action, b));
x.list_of_actions.connect(bind(&C::C_action, c));
请注意,我使用过bind
. 因此,list_of_actions 中的函数类型是相同的,但我们可以将它连接到不同类型的类。所以:
bind(&A::A_action, a)
这个东西产生了一个可调用的东西,其类型void ()
与我们之前声明的类型相同list_of actions
。当然,您在第二个参数中指定要应用此成员函数的实例。
如果您正在做多线程的事情,那么使用它的姐妹信号2 。
希望有帮助。