C++中的回调函数

431

在C++中,何时以及如何使用回调函数?

编辑:
我希望看到一个编写回调函数的简单示例。


3
这篇文章很好地解释了回调函数的基础知识,易于理解其概念。 - Anurag Singh
12个回答

672
注意:大多数答案涵盖了函数指针,这是在C++中实现“回调”逻辑的一种可能性,但我认为目前不是最受欢迎的方法。
什么是回调函数?为什么要使用它们?
回调函数是一个可调用对象(见下文),被类或函数接受,并根据该回调函数自定义当前逻辑。
使用回调函数的一个原因是编写独立于被调用函数中的逻辑的通用代码,并可以重复使用不同的回调函数。
标准算法库<algorithm>的许多函数都使用回调函数。例如,for_each算法将一元回调函数应用于迭代器范围中的每个项:
template<class InputIt, class UnaryFunction>
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f)
{
  for (; first != last; ++first) {
    f(*first);
  }
  return f;
}

可以通过传递相应的可调用对象,首先递增然后打印一个向量。

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

回调函数的另一个应用是通知调用者某些事件,从而实现一定程度的静态/编译时灵活性。
个人而言,我使用了一个本地优化库,它使用了两个不同的回调函数:
- 第一个回调函数在需要函数值和基于输入值向量的梯度时被调用(逻辑回调:确定函数值/导数推导)。 - 第二个回调函数在每个算法步骤中被调用,并接收有关算法收敛情况的特定信息(通知回调)。
因此,库设计者无需决定通过通知回调提供给程序员的信息将如何处理,也无需担心如何实际确定函数值,因为这些由逻辑回调提供。正确处理这些事项是库用户的任务,这使得库更加精简和通用。
此外,回调函数还可以实现动态运行时行为。
想象一下某种游戏引擎类,它有一个函数,在用户按下键盘上的按钮时触发,并有一组控制游戏行为的函数。通过回调函数,您可以在运行时重新决定采取哪种操作。
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 the menu
    void update_keybind(unsigned key_id, void(*new_action)())
    {
        actions[key_id] = new_action;
    }
};

这里的函数key_pressed使用存储在actions中的回调函数来实现在按下某个特定键时获得所需行为。 如果玩家选择更改跳跃按钮,引擎可以调用。
game_core_instance.update_keybind(newly_selected_key, &player_jump);

因此,一旦按下此按钮,将更改对key_pressed的调用行为(该调用会调用player_jump),并在下次游戏中生效。

C++(11)中的可调用对象是什么?

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

在C++(11)中,可以通过多种方式实现回调功能,因为有几种不同的东西被证明是可调用的*

  • 函数指针(包括成员函数指针)
  • std::function对象
  • Lambda表达式
  • 绑定表达式
  • 函数对象(具有重载的函数调用运算符operator()的类)

* 注意:数据成员指针也是可调用的,但根本不会调用任何函数。

详细介绍几种重要的编写回调函数的方法

  • X.1 在这篇文章中,“编写”回调指的是声明和命名回调类型的语法。
  • X.2 “调用”回调是指调用这些对象的语法。
  • X.3 “使用”回调是指在使用回调函数时传递参数的语法。

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

1. 函数指针

函数指针是回调函数可能具有的“最简单”(就广泛性而言;就可读性而言可能是最差的)类型。

让我们来看一个简单的函数foo

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

1.1 编写函数指针/类型表示法

一个函数指针类型的表示法如下:

return_type (*)(parameter_type_1, parameter_type_2, parameter_type_3)
// i.e. a pointer to foo has the type:
int (*)(int)

在C语言中,一个命名的函数指针类型看起来像这样
return_type (* name) (parameter_type_1, parameter_type_2, parameter_type_3)

// i.e. 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 a 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;

使用声明给了我们一个选择,使得代码更易读一些,因为对于 f_int_t 的 typedef 也可以写成:
using f_int_t = int(*)(int);

对我来说,f_int_t 是新的类型别名,函数指针类型的识别也更容易。
使用回调函数指针类型的函数声明将是:
// 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.3 回调使用符号和兼容类型

接受函数指针的回调函数可以使用函数指针进行调用。

使用接受函数指针回调的函数相当简单:

 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 示例
可以编写一个不依赖于回调函数工作方式的函数:
void tranform_every_int(int * v, unsigned n, int (*fp)(int))
{
  for (unsigned i = 0; i < n; ++i)
  {
    v[i] = fp(v[i]);
  }
}

在可能的情况下,回调函数可以是什么?
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 的成员函数的指针是一种特殊类型的(更加复杂的)函数指针,它需要一个 C 类型的对象来操作。

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

2.1 写指向成员函数/类型的表示法
一个类T的成员函数类型的指针具有以下表示法
// can have more or less parameters
return_type (T::*)(parameter_type_1, parameter_type_2, parameter_type_3)
// i.e. a pointer to C::foo has the type
int (C::*) (int)

在C++中,一个指向成员函数的命名指针将会和函数指针类似,形式如下:
return_type (T::* name) (parameter_type_1, parameter_type_2, parameter_type_3)

// i.e. a type `f_C_int` representing a pointer to a 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 a 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;

例子:声明一个函数,其中一个参数是成员函数回调的指针
// C_foobar having an argument named moo of type pointer to a 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 be declared using the typedef above:
int C_foobar (int x, C const &c, f_C_int_t moo);

2.2 回调函数调用表示法

对于类型为C的对象,可以通过对解引用的指针使用成员访问操作来调用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.3 回调使用符号和兼容类型
一个接受类T的成员函数指针作为回调函数的回调函数可以使用类T的成员函数指针进行调用。
与函数指针类似,使用接受成员函数指针的回调函数也是相当简单的。
 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对象(头文件<functional>std::function类是一个多态函数包装器,用于存储、复制或调用可调用对象。
3.1 编写std::function对象/类型表示法
存储可调用对象的std::function对象的类型如下:
std::function<return_type(parameter_type_1, parameter_type_2, parameter_type_3)>

// i.e. 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.3 回调函数使用符号和兼容类型

std::function回调函数比函数指针或成员函数指针更通用,因为可以传递不同类型并隐式转换为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 Lambda表达式

来自lambda表达式的无名闭包可以存储在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::bind 表达式

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

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. 模板化回调类型

使用模板,调用回调的代码可以比使用 std::function 对象更加通用。

请注意,模板是一种编译时特性,是一种用于编译时多态的设计工具。如果要通过回调实现运行时动态行为,模板可以帮助,但不会引入运行时动态。

4.1 编写(类型标注)和调用模板化回调

通过使用模板,可以进一步泛化上述代码中的 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]);
  }
}

对于回调类型,具有更通用(以及更简单)的语法是使用普通的、可推导的模板参数:

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

注意:所包含的输出打印了模板类型F的推断类型名称。type_name的实现在本文末尾给出。
对于范围的一元转换,最通用的实现是标准库的一部分,即std::transform,它也是针对迭代类型进行模板化的。
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 使用模板回调和兼容类型的示例
对于模板化的std::function回调方法stdf_transform_every_int_templ,其兼容类型与上述类型相同(参见3.4)。
然而,使用模板化版本时,所使用回调的签名可能会有些变化:
// 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 的普通模板参数可以是任何可调用类型。
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;
}
        

51
如果您还没有注意到:这个答案有两部分。1.关于"回调函数"的一般解释和一个小例子。2.一个全面的可调用对象列表和使用回调函数编写代码的方式。您可以选择不深入了解或者只阅读部分答案,但仅仅因为您不需要详细的信息,并不意味着这个答案是无效的或者是"brutally copied"(非常抄袭)。此话题是有关"C++ 回调函数"的。即使第一部分对 OP 来说已经足够了,其他人可能也会发现第二部分很有用。欢迎指出任何缺乏信息或建设性批评,而不是进行负面评价。 - Pixelchemist
34
@BogeyJammer 我并不是编程新手,但对于“现代C++”还算陌生。这篇回答为我提供了非常明确的背景信息,使我能够理解回调在特定情况下在C++中扮演的角色。尽管原帖可能没有要求多个实例,但在Stack Overflow上,为了永无止境地教育那些愚昧的世界,列举问题的所有可能解决方案是惯例。如果读起来像一本书,我唯一能提供的建议就是通过阅读其中几本书进行一点练习。 - dcow
1
int b = foobar(a, foo); // call foobar with pointer to foo as callback,这是一个错别字吧?我认为 foo 应该是一个指针才能使其正常工作。 - konoufo
1
@konoufo:C++11标准中的[conv.func]指出:“函数类型T的左值可以转换为类型为“指向T的指针”的prvalue。结果是一个指向函数的指针”。这是一种标准转换,因此会隐式发生。当然,人们可以在此处使用函数指针。 - Pixelchemist
请问有人能详细解释一下或者为我提供好的资源,来解释第一个代码块中发生了什么:template<class InputIt, class UnaryFunction> UnaryFunction for_each (...?特别是 UnaryFunction 的作用。非常感谢! - Milan
显示剩余5条评论

179

还有一种用 C 语言实现的回调方式:函数指针

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

现在,如果你想将类方法作为回调函数传递进去,那么这些函数指针的声明会更加复杂,例如:

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

2
类方法示例中存在错误。调用应该是: (instance.*callback)(1.0f) - CarlJohnson
3
这种方式与std::tr1:function相比的不足之处在于回调函数是按类别进行类型定义的;当执行调用的对象不知道被调用对象的类时,使用C风格的回调变得不切实际。 - bleater
1
@Milan 我刚刚投票反对了你最新的建议编辑,其摘要是“上一个编辑刚刚删除了有用的评论(甚至不关心撰写适当的概述。他/她只是复制粘贴了摘要!!)”。为了解释发生了什么:我打赌你试图撤销(由@Tarmo执行)的编辑来自于审核建议编辑的过程;审核员有机会“进一步编辑”你的提案,而这实际上显示为具有相同摘要的单独编辑(不幸的是)。 - Maëlan
1
现在,我来解释一下为什么我拒绝了你最新的编辑(因此同意Tarmo对你的第一个编辑所做的修改):原始答案描述了“C方式”,但using是C++的特性。不过,经过再次考虑,只要注释被编辑为清楚地说明using是C++而不是C,我就会接受它。 - Maëlan
1
@Milan 我同意。编辑审核的反馈有点有限。(我不能自己批准您的编辑,您需要审核的编辑是随机抽取的,而且我的配额已经用完了。) - Maëlan
显示剩余7条评论

79

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++ 回调函数的“现代”方式。


4
有趣的是,SM在哪本书中举了这个例子?谢谢 :) - sam-w
6
我知道这篇文章很老,但由于我曾经尝试过在我的设置(mingw)上进行此操作并最终失败了,所以如果你使用的是GCC版本<4.x,则不支持这种方法。一些我使用的依赖项在gcc版本>=4.0.1中无法编译,因此我只能使用老式的C风格回调函数,这种方法仍然可以正常工作。 - OzBarry

38

回调函数是一种传递给例程的方法,在被传递到的例程中某个时刻被调用。

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

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


72
这个回答并没有让普通程序员了解任何他不知道的东西。我正在学习C++,同时熟悉许多其他编程语言。回调函数一般是什么并不关系我。 - Tomáš Zato
问题是关于如何使用回调函数,而不是如何定义它们。 - Denis G. Labrecque

34

接受的答案非常有用而且相当全面。然而,OP表示:

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

所以在这里,从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;
}

这个例子有些实际意义,因为你希望用不同的哈希函数实现调用print_hashes函数,为此我提供了一个简单的哈希函数。它接收一个字符串,返回一个整数(提供的字符串的哈希值),从语法部分记住的是std::function<int (const std::string&)>,它描述了这样一个函数作为函数的输入参数,将调用它。


2
在所有上面的答案中,这个让我明白了回调函数是什么以及如何使用它们。谢谢。 - Mehar Charan Sahai
@MeharCharanSahai 很高兴听到这个好消息 :) 不用谢。 - Miljen Mikic
1
这让我最终明白了,谢谢。我认为有时候工程师们应该不那么严肃地对待它们,并理解最终的技能在于有意识地简化不简单的东西,依我看。 - Niki Romagnoli

12

在C++中,没有显式的回调函数概念。回调机制通常通过函数指针、函子对象或回调对象来实现。程序员必须明确设计和实现回调功能。

根据反馈进行编辑:

尽管这个答案收到了负面反馈,但并不是错误的。我会尝试更好地解释我的观点。

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

然而,回调函数和函数指针并不是同义词。函数指针是一种语言机制,而回调函数是一个语义概念。实现回调函数的方式不仅限于使用函数指针-您还可以使用functor甚至普通的虚函数。使函数调用成为回调的关键不是用于标识和调用函数的机制,而是调用的上下文和语义。说某些东西是回调函数意味着调用函数和被调用函数之间的分离程度大于正常水平,调用者对哪个函数被调用具有显式控制。正是这种模糊的概念松散的概念耦合和调用者驱动的函数选择使得某些东西成为回调函数,而不是使用函数指针。

例如,.NET文档中的IFormatProvider指出,"GetFormat是一个回调方法",即使它只是一个普通的接口方法。我不认为有人会认为所有虚方法调用都是回调函数。使GetFormat成为回调方法的是调用者选择调用哪个对象的GetFormat方法的语义,而不是它如何传递或调用的机制。

一些语言包含具有显式回调语义的功能,通常与事件和事件处理相关。例如,C#具有事件类型,其语法和语义明确设计为围绕回调概念。Visual Basic具有其 Handles 子句,它明确声明一个方法为回调函数,同时抽象出委托或函数指针的概念。在这些情况下,回调的语义概念被集成到语言本身中。

另一方面,C和C ++没有像回调函数的语义概念那样明确地嵌入。机制存在,但集成语义并不是那么明显。你可以很好地实现回调函数,但是要获得更复杂的东西,包括显式的回调语义,就必须建立在C++提供的基础之上,例如Qt使用了他们的信号和槽

简而言之,C++具有实现回调所需的内容,通常使用函数指针非常容易和琐碎。它没有特定于回调的关键字和功能的语义,如raiseemitHandlesevent +=等。如果你来自具有这些元素类型的语言,C++中的本地回调支持将感觉受限。


1
幸运的是,这不是我访问此页面时读到的第一个答案,否则我会立即离开! - ubugnu

6

1
回调函数并不一定意味着通过作为参数传递的函数指针执行函数是同义词。根据某些定义,回调函数这个术语还带有通知其他代码刚刚发生了什么或者现在应该发生什么的附加语义。从这个角度来看,回调函数不是 C 标准的一部分,但可以使用标准的函数指针轻松实现。 - Darryl
3
“part of the C standard, and therefore also part of C++.” 这是一个典型的误解,但仍然是一个误解 :-) - lmat - Reinstate Monica
我必须同意。如果我现在更改它,只会导致更多的混乱,所以我将保持原样。我的意思是函数指针(!)是标准的一部分。说与此不同的任何内容 - 我同意 - 都是误导性的。 - AudioDroid
回调函数“是C标准的一部分”有什么依据?我认为它支持函数和指向函数的指针并不意味着它特别将回调作为语言概念规范化。此外,正如提到的那样,即使准确,这也与C++没有直接关系。而且当OP询问在C++中“何时以及如何”使用回调时(一个无聊、过于广泛的问题,但仍然),你的答案只是一个链接,告诫要做一些不同的事情。 - underscore_d

5
请看上面的定义,其中指出回调函数被传递到另一个函数中,并在某个时刻被调用。
在C++中,希望回调函数调用类的方法。这样做可以访问成员数据。如果使用C语言的方式定义回调,必须将其指向静态成员函数。这是不太理想的。
以下是如何在C++中使用回调的方法。假设有4个文件,每个类都有一对.CPP/.H文件。C1是要回调的类,C2回调C1的方法。在此示例中,回调函数需要一个参数,我为读者添加了此参数。示例未显示实例化和使用任何对象。这种实现的一个用例是当一个类读取并存储数据到临时空间,另一个类对数据进行后处理时。通过回调函数,每读取一行数据,回调就可以处理它。这种技术减少了所需的临时空间开销。特别适用于返回大量数据并需要进行后处理的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);
}

1
接受的答案很全面,但与我的问题相关。我只想在这里提供一个简单的例子。我有一段很久以前写的代码。我想以中序遍历的方式(左节点,根节点,右节点)遍历一棵树,并且每当我到达一个节点时,我希望能够调用任意函数,以便它可以执行所有操作。
void inorder_traversal(Node *p, void *out, void (*callback)(Node *in, void *out))
{
    if (p == NULL)
        return;
    inorder_traversal(p->left, out, callback);
    callback(p, out); // call callback function like this.
    inorder_traversal(p->right, out, callback);
}


// Function like bellow can be used in callback of inorder_traversal.
void foo(Node *t, void *out = NULL)
{
    // You can just leave the out variable and working with specific node of tree. like bellow.
    // cout << t->item;
    // Or
    // You can assign value to out variable like below
    // Mention that the type of out is void * so that you must firstly cast it to your proper out.
    *((int *)out) += 1;
}
// This function use inorder_travesal function to count the number of nodes existing in the tree.
void number_nodes(Node *t)
{
    int sum = 0;
    inorder_traversal(t, &sum, foo);
    cout << sum;
}

 int main()
{

    Node *root = NULL;
    // What These functions perform is inserting an integer into a Tree data-structure.
    root = insert_tree(root, 6);
    root = insert_tree(root, 3);
    root = insert_tree(root, 8);
    root = insert_tree(root, 7);
    root = insert_tree(root, 9);
    root = insert_tree(root, 10);
    number_nodes(root);
}

1
它如何回答这个问题? - Rajan Sharma
1
你知道被接受的答案是正确和全面的,我认为一般来说没有更多要说的了。但我会发布一个回调函数使用示例。 - Ehsan Ahmadi

0

Boost的signals2允许您以线程安全的方式订阅通用成员函数(无需模板!)。

示例:文档-视图信号可用于实现灵活的文档-视图架构。文档将包含一个信号,每个视图都可以连接到该信号。以下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;
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接