在c ++中有任何事件/代理/接口/通知!什么?

Bac*_*ach 7 c++ callback signals-slots

说我有这些类ViewA和ViewB

在目标C中使用委托模式我可以做到

@protocol ViewBDelegate{

- (void) doSomething();
}
Run Code Online (Sandbox Code Playgroud)

然后在ViewB界面中:

id<ViewBDelegate> delegate;
Run Code Online (Sandbox Code Playgroud)

然后在ViewA实现中我设置了委托:

viewB.delegate = self;
Run Code Online (Sandbox Code Playgroud)

现在我可以从viewB调用doSomething到任何未知类型的委托.

[delegate doSomething];
Run Code Online (Sandbox Code Playgroud)

"C++如何编程"是一个更糟糕的读物,无法找到演示基本设计模式的简单例子.

我在C++中寻找的是:

  • 事件 ActionScript和java
  • 或目标C中的代表或NSNotifications

任何允许A类,B类和C类知道ClassX didSomething()的东西!

谢谢

Ara*_*raK 9

如果我是你,我不会使用函数指针来完成这个任务.将此选项留给大师;)

在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();
}
Run Code Online (Sandbox Code Playgroud)

这将打印:

Hello I am X!
A::A_action();
B::B_action();
C::C_action();
Run Code Online (Sandbox Code Playgroud)

下面是它的工作原理.

首先,声明保存委托的位置:

signal<void()> list_of_actions;
Run Code Online (Sandbox Code Playgroud)

然后,您将它"连接"到您想要调用的任何函数/函子/可调用事物组.

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));
Run Code Online (Sandbox Code Playgroud)

请注意,我已经使用过bind.因此,list_of_actions中的函数类型是相同的,但我们可以将它连接到不同类型的类.所以:

bind(&A::A_action, a)
Run Code Online (Sandbox Code Playgroud)

这个东西,产生一个可调用的东西,类型,void ()因为我们声明了list_of actions早期的类型.当然,您在第二个参数中指定要应用此成员函数的实例.

如果你正在做多线程的东西,那么使用它的姐妹信号2.

希望有所帮助.


sml*_*sml 5

任何允许A类,B类和C类知道ClassX didSomething()的东西!

您可能正在寻找具有多种实现的信号和插槽:

我相信还有更多,但这些是我所知道的最重要的.