在c ++中的callback函数

在c ++中,何时以及如何使用callback函数?

编辑:
我想看一个简单的例子来编写一个callback函数。

注意:大部分的答案都包含了函数指针,这是C ++中实现“callback”逻辑的一种可能,但是到目前为止,还不是我认为最有利的一种。

什么是callback(?)以及为什么要使用它们(!)

callback函数是一个类或函数接受的可调用函数(详见下文),用于根据callback函数定制当前逻辑。

使用callback的一个原因是编写与被调用函数中的逻辑无关的通用代码,并且可以用不同的callback重用。

标准algorithm库的许多function<algorithm>使用callback函数。 例如, for_eachalgorithm对一系列迭代器中的每个项目应用一元callback:

 template<class InputIt, class UnaryFunction> UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f) { for (; first != last; ++first) { f(*first); } return f; } 

可以用来先递增,然后打印一个vector,例如传递适当的可调用元素:

 std::vector<double> v{ 1.0, 2.2, 4.0, 5.5, 7.2 }; double r = 4.0; std::for_each(v.begin(), v.end(), [&](double & v) { v += r; }); std::for_each(v.begin(), v.end(), [](double v) { std::cout << v << " "; }); 

打印

 5 6.2 8 9.5 11.2 

callback的另一个应用是通知某些事件的调用者,这使得静态/编译时间具有一定的灵活性。

就我个人而言,我使用了一个使用两个不同callback的本地优化库:

  • 如果需要函数值和基于input值向量的梯度(逻辑callback:函数值确定/梯度推导),则调用第一个callback函数。
  • 每个algorithm步骤调用第二次callback,并接收有关algorithm收敛的一些信息(通知callback)。

因此,库devise者不负责决定通过通知callback给予程序员的信息会发生什么情况,他不必担心如何通过逻辑callback来提供函数值。 把这些事情做好是图书馆用户的一项任务,并保持图书馆的苗条和更通用。

此外,callback可以启用dynamic运行时行为。

想象一下某种types的游戏引擎类,它有一个被触发的函数,每次用户按下键盘上的一个button和一组控制游戏行为的函数。 通过callback,您可以(在运行时)决定采取何种行动。

 void player_jump(); void player_crouch(); class game_core { std::array<void(*)(), total_num_keys> actions; // void key_pressed(unsigned key_id) { if(actions[key_id]) actions[key_id](); } // update keybind from menu void update_keybind(unsigned key_id, void(*new_action)()) { actions[key_id] = new_action; } }; 

在这里, key_pressed函数使用存储在actions的callback来获得当某个键被按下时所需的行为。 如果玩家select改变跳跃的button,引擎可以调用

 game_core_instance.update_keybind(newly_selected_key, &player_jump); 

并因此在下一次游戏中按下该button之后,改变对key_pressed (其调用player_jump )的调用的行为。

C ++(11)中的可调用函数是什么?

请参阅C ++概念:可在cppreference上调用以获得更正式的描述。

callback函数可以通过几种方式在C ++(11)中实现,因为几个不同的事情变成可调用*

  • 函数指针(包括指向成员函数的指针)
  • std::function对象
  • Lambdaexpression式
  • 绑定expression式
  • 函数对象(具有重载函数调用operator operator()

* 注意:指向数据成员的指针也可以调用,但是根本没有函数被调用。

几个重要的方法来详细写callback

  • X.1在这篇文章中“写”callback意味着声明和命名callbacktypes的语法。
  • X.2“调用”callback是指调用这些对象的语法。
  • X.3“使用”callback意味着使用callback函数将parameter passing给函数时的语法。

注意:从C ++ 17开始,像f(...)这样的调用可以写成std::invoke(f, ...) ,它也处理指向成员大小写的指针。

1.函数指针

函数指针是“最简单的”(就通用性而言,在可读性方面可以说是最差的)types的callback可以有。

让我们有一个简单的函数foo

 int foo (int x) { return 2+x; } 

1.1编写一个函数指针/types表示法

函数指针types有符号

 return_type (*)(paramter_type_1, paramter_type_2, paramter_type_3) // ie a pointer to foo has the type: int (*)(int) 

一个命名的函数指针types看起来像

 return_type (* name) (paramter_type_1, paramter_type_2, paramter_type_3) // ie f_int_t is a type: function pointer taking one int argument, returning int typedef int (*f_int_t) (int); // foo_p is a pointer to function taking int returning int // initialized by pointer to function foo taking int returning int int (* foo_p)(int) = &foo; // can alternatively be written as f_int_t foo_p = &foo; 

using声明使我们可以select使事情更具可读性,因为f_int_ttypedef也可以写成:

 using f_int_t = int(*)(int); 

在哪里(至less对我来说) f_int_t是新的types别名更清楚,并且函数指针types的识别也更容易

使用函数指针types的callback函数的声明将是:

 // foobar having a callback argument named moo of type // pointer to function returning int taking int as its argument int foobar (int x, int (*moo)(int)); // if f_int is the function pointer typedef from above we can also write foobar as: int foobar (int x, f_int_t moo); 

1.2回拨呼叫标记

调用符号遵循简单的函数调用语法:

 int foobar (int x, int (*moo)(int)) { return x + moo(x); // function pointer moo called using argument x } // analog int foobar (int x, f_int_t moo) { return x + moo(x); // function pointer moo called using argument x } 

1.3callback使用符号和兼容types

采用函数指针的callback函数可以使用函数指针调用。

使用一个函数指针callback函数是相当简单的:

  int a = 5; int b = foobar(a, foo); // call foobar with pointer to foo as callback // can also be int b = foobar(a, &foo); // call foobar with pointer to foo as callback 

1.4例子

一个函数可以写成,不依赖于callback的工作方式:

 void tranform_every_int(int * v, unsigned n, int (*fp)(int)) { for (unsigned i = 0; i < n; ++i) { v[i] = fp(v[i]); } } 

在可能的情况下callback可能是

 int double_int(int x) { return 2*x; } int square_int(int x) { return x*x; } 

用过

 int a[5] = {1, 2, 3, 4, 5}; tranform_every_int(&a[0], 5, double_int); // now a == {2, 4, 6, 8, 10}; tranform_every_int(&a[0], 5, square_int); // now a == {4, 16, 36, 64, 100}; 

2.指向成员函数

成员函数指针(某些类C )是一个特殊types的(甚至更复杂的)函数指针,它需要typesC的对象来操作。

 struct C { int y; int foo(int x) const { return x+y; } }; 

2.1将指针写入成员函数/types表示法

对于某些类T ,成员函数types的指针具有符号

 // can have more or less parameters return_type (T::*)(paramter_type_1, paramter_type_2, paramter_type_3) // ie a pointer to C::foo has the type int (C::*) (int) 

在这里,一个指向成员函数的指向指针将类似于函数指针,看起来像这样:

 return_type (T::* name) (paramter_type_1, paramter_type_2, paramter_type_3) // ie a type `f_C_int` representing a pointer to member function of `C` // taking int returning int is: typedef int (C::* f_C_int_t) (int x); // The type of C_foo_p is a pointer to member function of C taking int returning int // Its value is initialized by a pointer to foo of C int (C::* C_foo_p)(int) = &C::foo; // which can also be written using the typedef: f_C_int_t C_foo_p = &C::foo; 

示例:声明一个将成员函数callback指针作为参数的函数:

 // C_foobar having an argument named moo of type pointer to member function of C // where the callback returns int taking int as its argument // also needs an object of type c int C_foobar (int x, C const &c, int (C::*moo)(int)); // can equivalently declared using the typedef above: int C_foobar (int x, C const &c, f_C_int_t moo); 

2.2回拨呼叫标记

通过在解除引用的指针上使用成员访问操作,可以调用指向C成员函数的指针。 注意:必须使用括号!

 int C_foobar (int x, C const &c, int (C::*moo)(int)) { return x + (c.*moo)(x); // function pointer moo called for object c using argument x } // analog int C_foobar (int x, C const &c, f_C_int_t moo) { return x + (c.*moo)(x); // function pointer moo called for object c using argument x } 

注意:如果指向C的指针可用,则语法是相同的( C指针也必须解除引用):

 int C_foobar_2 (int x, C const * c, int (C::*meow)(int)) { if (!c) return x; // function pointer meow called for object *c using argument x return x + ((*c).*meow)(x); } // or equivalent: int C_foobar_2 (int x, C const * c, int (C::*meow)(int)) { if (!c) return x; // function pointer meow called for object *c using argument x return x + (c->*meow)(x); } 

2.3callback使用符号和兼容types

采用类T的成员函数指针的callback函数可以使用类T的成员函数指针调用。

使用一个接受成员函数callback的指针的函数,类似于函数指针,也很简单:

  C my_c{2}; // aggregate initialization int a = 5; int b = C_foobar(a, my_c, &C::foo); // call C_foobar with pointer to foo as its callback 

3. std::function对象(header <functional>

std::function类是一个存储,复制或调用可调用的多态函数包装器。

3.1编写一个std::function对象/types表示法

存储可调用对象的std::function对象的types如下所示:

 std::function<return_type(paramter_type_1, paramter_type_2, paramter_type_3)> // ie using the above function declaration of foo: std::function<int(int)> stdf_foo = &foo; // or C::foo: std::function<int(const C&, int)> stdf_C_foo = &C::foo; 

3.2回拨呼叫标记

std::function类定义了可以用来调用其目标的operator()

 int stdf_foobar (int x, std::function<int(int)> moo) { return x + moo(x); // std::function moo called } // or int stdf_C_foobar (int x, C const &c, std::function<int(C const &, int)> moo) { return x + moo(c, x); // std::function moo called using c and x } 

3.3callback使用符号和兼容types

std::functioncallback比函数指针或指向成员函数的指针更通用,因为可以传递不同的types并隐式转换为std::function对象。

3.3.1函数指针和成员函数的指针

一个函数指针

 int a = 2; int b = stdf_foobar(a, &foo); // b == 6 ( 2 + (2+2) ) 

或者一个指向成员函数的指针

 int a = 2; C my_c{7}; // aggregate initialization int b = stdf_C_foobar(a, c, &C::foo); // b == 11 == ( 2 + (7+2) ) 

可以使用。

3.3.2 Lambdaexpression式

来自lambdaexpression式的未命名的闭包可以存储在std::function对象中:

 int a = 2; int c = 3; int b = stdf_foobar(a, [c](int x) -> int { return 7+c*x; }); // b == 15 == a + (7*c*a) == 2 + (7+3*2) 

3.3.3 std::bindexpression式

可以传递std::bindexpression式的结果。 例如通过将参数绑定到函数指针调用:

 int foo_2 (int x, int y) { return 9*x + y; } using std::placeholders::_1; int a = 2; int b = stdf_foobar(a, std::bind(foo_2, _1, 3)); // b == 23 == 2 + ( 9*2 + 3 ) int c = stdf_foobar(a, std::bind(foo_2, 5, _1)); // c == 49 == 2 + ( 9*5 + 2 ) 

也可以将对象绑定为指向成员函数的指针的对象:

 int a = 2; C const my_c{7}; // aggregate initialization int b = stdf_foobar(a, std::bind(&C::foo, my_c, _1)); // b == 1 == 2 + ( 2 + 7 ) 

3.3.4函数对象

具有适当的operator()重载的类的对象也可以存储在一个std::function对象中。

 struct Meow { int y = 0; Meow(int y_) : y(y_) {} int operator()(int x) { return y * x; } }; int a = 11; int b = stdf_foobar(a, Meow{8}); // b == 99 == 11 + ( 8 * 11 ) 

3.4例子

更改函数指针示例以使用std::function

 void stdf_tranform_every_int(int * v, unsigned n, std::function<int(int)> fp) { for (unsigned i = 0; i < n; ++i) { v[i] = fp(v[i]); } } 

因为(见3.3),我们有更多的可能性来使用它:

 // using function pointer still possible int a[5] = {1, 2, 3, 4, 5}; stdf_tranform_every_int(&a[0], 5, double_int); // now a == {2, 4, 6, 8, 10}; // use it without having to write another function by using a lambda stdf_tranform_every_int(&a[0], 5, [](int x) -> int { return x/2; }); // now a == {1, 2, 3, 4, 5}; again // use std::bind : int nine_x_and_y (int x, int y) { return 9*x + y; } using std::placeholders::_1; // calls nine_x_and_y for every int in a with y being 4 every time stdf_tranform_every_int(&a[0], 5, std::bind(nine_x_and_y, _1, 4)); // now a == {13, 22, 31, 40, 49}; 

4.模板化的callbacktypes

使用模板,调用callback的代码比使用std::function对象更普遍。

请注意,模板是一个编译时function,是编译时多态的devise工具。 如果要通过callback来实现运行时dynamic行为,模板将会有所帮助,但是它们不会引发运行时dynamic。

4.1编写(键入符号)和调用模板callback

通过使用模板来进一步推广即使更进一步的std_ftransform_every_int代码也可以实现:

 template<class R, class T> void stdf_transform_every_int_templ(int * v, unsigned const n, std::function<R(T)> fp) { for (unsigned i = 0; i < n; ++i) { v[i] = fp(v[i]); } } 

对于一个callbacktypes来说,更一般的(也是最简单的)语法是一个普通的,将被推断的模板化的论点:

 template<class F> void transform_every_int_templ(int * v, unsigned const n, F f) { std::cout << "transform_every_int_templ<" << type_name<F>() << ">\n"; for (unsigned i = 0; i < n; ++i) { v[i] = f(v[i]); } } 

注意:包含的输出将打印为模板typesF推导的types名称。 在这篇文章的最后给出了type_name的实现。

范围的一元转换的最一般的实现是标准库的一部分,也就是std::transform ,它也是迭代types的模板。

 template<class InputIt, class OutputIt, class UnaryOperation> OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first, UnaryOperation unary_op) { while (first1 != last1) { *d_first++ = unary_op(*first1++); } return d_first; } 

4.2使用模板callback和兼容types的示例

模板化的std::functioncallback方法stdf_transform_every_int_templ的兼容types与上面提到的types相同(见3.4)。

但是,使用模板版本,所使用的callback的签名可能会有所变化:

 // Let int foo (int x) { return 2+x; } int muh (int const &x) { return 3+x; } int & woof (int &x) { x *= 4; return x; } int a[5] = {1, 2, 3, 4, 5}; stdf_transform_every_int_templ<int,int>(&a[0], 5, &foo); // a == {3, 4, 5, 6, 7} stdf_transform_every_int_templ<int, int const &>(&a[0], 5, &muh); // a == {6, 7, 8, 9, 10} stdf_transform_every_int_templ<int, int &>(&a[0], 5, &woof); 

注意: std_ftransform_every_int (非模板版本;见上)与foo工作,但不使用muh

 // Let void print_int(int * p, unsigned const n) { bool f{ true }; for (unsigned i = 0; i < n; ++i) { std::cout << (f ? "" : " ") << p[i]; f = false; } std::cout << "\n"; } 

transform_every_int_templ模板参数可以是任何可能的可调用types。

 int a[5] = { 1, 2, 3, 4, 5 }; print_int(a, 5); transform_every_int_templ(&a[0], 5, foo); print_int(a, 5); transform_every_int_templ(&a[0], 5, muh); print_int(a, 5); transform_every_int_templ(&a[0], 5, woof); print_int(a, 5); transform_every_int_templ(&a[0], 5, [](int x) -> int { return x + x + x; }); print_int(a, 5); transform_every_int_templ(&a[0], 5, Meow{ 4 }); print_int(a, 5); using std::placeholders::_1; transform_every_int_templ(&a[0], 5, std::bind(foo_2, _1, 3)); print_int(a, 5); transform_every_int_templ(&a[0], 5, std::function<int(int)>{&foo}); print_int(a, 5); 

上面的代码打印:

 1 2 3 4 5 transform_every_int_templ <int(*)(int)> 3 4 5 6 7 transform_every_int_templ <int(*)(int&)> 6 8 10 12 14 transform_every_int_templ <int& (*)(int&)> 9 11 13 15 17 transform_every_int_templ <main::{lambda(int)#1} > 27 33 39 45 51 transform_every_int_templ <Meow> 108 132 156 180 204 transform_every_int_templ <std::_Bind<int(*(std::_Placeholder<1>, int))(int, int)>> 975 1191 1407 1623 1839 transform_every_int_templ <std::function<int(int)>> 977 1193 1409 1625 1841 

上面使用的type_name实现

 #include <type_traits> #include <typeinfo> #include <string> #include <memory> #include <cxxabi.h> template <class T> std::string type_name() { typedef typename std::remove_reference<T>::type TR; std::unique_ptr<char, void(*)(void*)> own (abi::__cxa_demangle(typeid(TR).name(), nullptr, nullptr, nullptr), std::free); std::string r = own != nullptr?own.get():typeid(TR).name(); if (std::is_const<TR>::value) r += " const"; if (std::is_volatile<TR>::value) r += " volatile"; if (std::is_lvalue_reference<T>::value) r += " &"; else if (std::is_rvalue_reference<T>::value) r += " &&"; return r; } 

还有C做callback的方式:函数指针

 //Define a type for the callback signature, //it is not necessary, but makes life easier //Function pointer called CallbackType that takes a float //and returns an int typedef int (*CallbackType)(float); void DoWork(CallbackType callback) { float variable = 0.0f; //Do calculations //Call the callback with the variable, and retrieve the //result int result = callback(variable); //Do something with the result } int SomeCallback(float variable) { int result; //Interpret variable return result; } int main(int argc, char ** argv) { //Pass in SomeCallback to the DoWork DoWork(&SomeCallback); } 

现在,如果您想以callback方式传递类方法,则对这些函数指针的声明具有更复杂的声明,例如:

 //Declaration: typedef int (ClassName::*CallbackType)(float); //This method performs work using an object instance void DoWorkObject(CallbackType callback) { //Class instance to invoke it through ClassName objectInstance; //Invocation int result = (objectInstance.*callback)(1.0f); } //This method performs work using an object pointer void DoWorkPointer(CallbackType callback) { //Class pointer to invoke it through ClassName * pointerInstance; //Invocation int result = (pointerInstance->*callback)(1.0f); } int main(int argc, char ** argv) { //Pass in SomeCallback to the DoWork DoWorkObject(&ClassName::Method); DoWorkPointer(&ClassName::Method); } 

Scott Meyers给出了一个很好的例子:

 class GameCharacter; int defaultHealthCalc(const GameCharacter& gc); class GameCharacter { public: typedef std::function<int (const GameCharacter&)> HealthCalcFunc; explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc) : healthFunc(hcf) { } int healthValue() const { return healthFunc(*this); } private: HealthCalcFunc healthFunc; }; 

我认为这个例子说明了一切。

std::function<>是编写C ++callback的“现代”方式。

一个callback函数是一个传入一个例程的方法,并在某个时刻被传入的例程调用。

这对于制作可重用的软件非常有用。 例如,许多操作系统API(例如Windows API)大量使用callback。

例如,如果您想处理文件夹中的文件 – 您可以使用自己的例程调用API函数,并且您的例程将在指定文件夹中的每个文件运行一次。 这使得API非常灵活。

被接受的答案是非常有用和相当全面的。 然而,OP说

我想看一个简单的例子来编写一个callback函数。

所以在这里,从C ++ 11开始,你有std::function所以不需要函数指针和类似的东西:

 #include <functional> #include <string> #include <iostream> void print_hashes(std::function<int (const std::string&)> hash_calculator) { std::string strings_to_hash[] = {"you", "saved", "my", "day"}; for(auto s : strings_to_hash) std::cout << s << ":" << hash_calculator(s) << std::endl; } int main() { print_hashes( [](const std::string& str) { /** lambda expression */ int result = 0; for (int i = 0; i < str.length(); i++) result += pow(31, i) * str.at(i); return result; }); return 0; } 

这个例子是某种程度上真实的,因为你希望使用hash函数的不同实现来调用函数print_hashes ,为此我提供了一个简单的例子。 它接收一个string,返回一个int(提供的string的散列值),而你需要记住的语法部分是std::function<int (const std::string&)> ,它描述了这样的函数input参数将调用它的函数。

callback函数是C标准的一部分,因此也是C ++的一部分。 但是如果你正在使用C ++,我build议你使用观察者模式 : http : //en.wikipedia.org/wiki/Observer_pattern

在C ++中没有一个callback函数的明确概念。 callback机制通常通过函数指针,函数对象或callback对象来实现。 程序员必须明确地devise和实现callback函数。

根据反馈编辑:

尽pipe这个答案已经收到了负面的反馈,但这并没有错。 我会尽力解释我来自哪里。

C和C ++拥有实现callback函数所需的一切。 实现callback函数的最常见和最简单的方法是传递函数指针作为函数参数。

但是,callback函数和函数指针并不是同义词。 函数指针是一种语言机制,而callback函数是一个语义概念。 函数指针并不是实现callback函数的唯一方法 – 你也可以使用函子,甚至花园变化的虚函数。 什么使一个函数调用callback不是用于标识和调用函数的机制,而是调用的上下文和语义。 说某事是一个callback函数意味着在调用函数和被调用的特定函数之间有一个比正常的更大的分隔,调用者和被调用者之间的松散的概念耦合,调用者明确地控制被调用的内容。 这是松散的概念耦合和调用者驱动的函数select的模糊概念,使得一些callback函数,而不是使用函数指针。

例如, IFormatProvider的.NET文档说“GetFormat是一个callback方法” ,即使它只是一个普通的界面方法。 我不认为有人会争辩说,所有的虚拟方法调用都是callback函数。 使GetFormat成为callback方法的不是它如何传递或调用的机制,而是调用者select哪个对象的GetFormat方法的语义。

某些语言包含显式callback语义的function,通常与事件和事件处理有关。 例如,C#具有事件types,语法和语义是围绕callback的概念明确devise的。 Visual Basic有它的Handles子句,在抽象出委托或函数指针的概念的同时,显式声明了一个方法是一个callback函数。 在这些情况下,callback的语义概念被整合到语言本身中。

另一方面,C和C ++几乎没有明确地embeddedcallback函数的语义概念 。 机制在那里,集成的语义不是。 你可以很好地实现callback函数,但是为了得到更复杂的东西,包括显式的callback语义,你必须在C ++提供的基础上构build它,比如Qt在它们的信号和插槽上做了什么。

简而言之,C ++具有实现callback所需的东西,通常使用函数指针可以非常轻松和简单。 它没有的关键字和特征的语义特定于callback,比如raiseemitHandlesevent + =等等。如果你使用这些types的元素来进行语言编程,那么C ++中的本地callback支持会感到无能为力

看到上面的定义,它指出一个callback函数被传递给其他某个函数,并在某个时候被调用。

在C ++中,最好有callback函数调用类方法。 当你这样做时,你可以访问成员数据。 如果使用定义callback的C方法,则必须将其指向静态成员函数。 这不是很理想。

这里是你如何在C ++中使用callback。 假设4个文件。 每个类的一对.CPP / .H文件。 类C1是一个我们想要callback的方法。 C2callback到C1的方法。 在这个例子中,callback函数需要1个参数,我为读者添加了这个参数。 该示例不显示任何正在实例化和使用的对象。 这种实现的一个用例是当你有一个类读取和存储数据到临时空间,另一个是后处理数据。 使用callback函数,对于读取的每一行数据,callback可以对其进行处理。 这种技术削减了所需临时空间的开销。 这对于返回大量数据然后必须被后处理的SQL查询特别有用。

 ///////////////////////////////////////////////////////////////////// // C1 H file class C1 { public: C1() {}; ~C1() {}; void CALLBACK F1(int i); }; ///////////////////////////////////////////////////////////////////// // C1 CPP file void CALLBACK C1::F1(int i) { // Do stuff with C1, its methods and data, and even do stuff with the passed in parameter } ///////////////////////////////////////////////////////////////////// // C2 H File class C1; // Forward declaration class C2 { typedef void (CALLBACK C1::* pfnCallBack)(int i); public: C2() {}; ~C2() {}; void Fn(C1 * pThat,pfnCallBack pFn); }; ///////////////////////////////////////////////////////////////////// // C2 CPP File void C2::Fn(C1 * pThat,pfnCallBack pFn) { // Call a non-static method in C1 int i = 1; (pThat->*pFn)(i); } 

Boost的singals2允许你订阅通用的成员函数(没有模板),并以线程安全的方式。

示例:文档视图信号可用于实现灵活的文档视图体系结构。 文档将包含每个视图可以连接的信号。 以下Document类定义了一个支持多视图的简单文本文档。 请注意,它存储所有视图将连接到的单个信号。

 class Document { public: typedef boost::signals2::signal<void ()> signal_t; public: Document() {} /* Connect a slot to the signal which will be emitted whenever text is appended to the document. */ boost::signals2::connection connect(const signal_t::slot_type &subscriber) { return m_sig.connect(subscriber); } void append(const char* s) { m_text += s; m_sig(); } const std::string& getText() const { return m_text; } private: signal_t m_sig; std::string m_text; }; 

接下来,我们可以开始定义视图。 以下TextView类提供了文档文本的简单视图。

 class TextView { public: TextView(Document& doc): m_document(doc) { m_connection = m_document.connect(boost::bind(&TextView::refresh, this)); } ~TextView() { m_connection.disconnect(); } void refresh() const { std::cout << "TextView: " << m_document.getText() << std::endl; } private: Document& m_document; boost::signals2::connection m_connection; };