在C++中,何时以及如何使用回调函数?
编辑:
我希望看到一个编写回调函数的简单示例。
在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
),并在下次游戏中生效。
请参阅cppreference上的C++概念:可调用对象以获取更正式的描述。
在C++(11)中,可以通过多种方式实现回调功能,因为有几种不同的东西被证明是可调用的*:
std::function
对象operator()
的类)* 注意:数据成员指针也是可调用的,但根本不会调用任何函数。
注意:从C++17开始,像f(...)
这样的调用可以写成std::invoke(f, ...)
,它还处理了成员指针的情况。
函数指针是回调函数可能具有的“最简单”(就广泛性而言;就可读性而言可能是最差的)类型。
让我们来看一个简单的函数foo
:
int foo (int x) { return 2+x; }
一个函数指针类型的表示法如下:
return_type (*)(parameter_type_1, parameter_type_2, parameter_type_3)
// i.e. a pointer to foo has the type:
int (*)(int)
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;
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);
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
}
接受函数指针的回调函数可以使用函数指针进行调用。
使用接受函数指针回调的函数相当简单:
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
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};
指向某个类 C
的成员函数的指针是一种特殊类型的(更加复杂的)函数指针,它需要一个 C
类型的对象来操作。
struct C
{
int y;
int foo(int x) const { return x+y; }
};
// 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)
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);
对于类型为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);
}
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
std::function
对象(头文件<functional>
)
std::function
类是一个多态函数包装器,用于存储、复制或调用可调用对象。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;
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
}
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 )
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 )
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]);
}
}
// 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};
使用模板,调用回调的代码可以比使用 std::function
对象更加通用。
请注意,模板是一种编译时特性,是一种用于编译时多态的设计工具。如果要通过回调实现运行时动态行为,模板可以帮助,但不会引入运行时动态。
通过使用模板,可以进一步泛化上述代码中的 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]);
}
}
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;
}
// 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);
// 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;
}
int b = foobar(a, foo); // call foobar with pointer to foo as callback
,这是一个错别字吧?我认为 foo
应该是一个指针才能使其正常工作。 - konoufo[conv.func]
指出:“函数类型T的左值可以转换为类型为“指向T的指针”的prvalue。结果是一个指向函数的指针”。这是一种标准转换,因此会隐式发生。当然,人们可以在此处使用函数指针。 - Pixelchemisttemplate<class InputIt, class UnaryFunction> UnaryFunction for_each (...
?特别是 UnaryFunction
的作用。非常感谢! - Milan还有一种用 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);
}
using
是C++的特性。不过,经过再次考虑,只要注释被编辑为清楚地说明using
是C++而不是C,我就会接受它。 - MaëlanScott 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++ 回调函数的“现代”方式。
回调函数是一种传递给例程的方法,在被传递到的例程中某个时刻被调用。
这对于制作可重复使用的软件非常有用。例如,许多操作系统API(如Windows API)大量使用回调函数。
例如,如果您想在文件夹中处理文件,则可以调用一个API函数,并使用您自己的例程,您的例程将针对指定文件夹中的每个文件运行一次。这使得API非常灵活。
接受的答案非常有用而且相当全面。然而,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&)>
,它描述了这样一个函数作为函数的输入参数,将调用它。
在C++中,没有显式的回调函数概念。回调机制通常通过函数指针、函子对象或回调对象来实现。程序员必须明确设计和实现回调功能。
根据反馈进行编辑:
尽管这个答案收到了负面反馈,但并不是错误的。我会尝试更好地解释我的观点。
C和C ++拥有实现回调函数所需的一切。最常见和简单的实现回调函数的方式是将函数指针作为函数参数传递。
然而,回调函数和函数指针并不是同义词。函数指针是一种语言机制,而回调函数是一个语义概念。实现回调函数的方式不仅限于使用函数指针-您还可以使用functor甚至普通的虚函数。使函数调用成为回调的关键不是用于标识和调用函数的机制,而是调用的上下文和语义。说某些东西是回调函数意味着调用函数和被调用函数之间的分离程度大于正常水平,调用者对哪个函数被调用具有显式控制。正是这种模糊的概念松散的概念耦合和调用者驱动的函数选择使得某些东西成为回调函数,而不是使用函数指针。
例如,.NET文档中的IFormatProvider指出,"GetFormat是一个回调方法",即使它只是一个普通的接口方法。我不认为有人会认为所有虚方法调用都是回调函数。使GetFormat成为回调方法的是调用者选择调用哪个对象的GetFormat方法的语义,而不是它如何传递或调用的机制。
一些语言包含具有显式回调语义的功能,通常与事件和事件处理相关。例如,C#具有事件类型,其语法和语义明确设计为围绕回调概念。Visual Basic具有其 Handles 子句,它明确声明一个方法为回调函数,同时抽象出委托或函数指针的概念。在这些情况下,回调的语义概念被集成到语言本身中。
另一方面,C和C ++没有像回调函数的语义概念那样明确地嵌入。机制存在,但集成语义并不是那么明显。你可以很好地实现回调函数,但是要获得更复杂的东西,包括显式的回调语义,就必须建立在C++提供的基础之上,例如Qt使用了他们的信号和槽。
简而言之,C++具有实现回调所需的内容,通常使用函数指针非常容易和琐碎。它没有特定于回调的关键字和功能的语义,如raise,emit,Handles,event +=等。如果你来自具有这些元素类型的语言,C++中的本地回调支持将感觉受限。
回调函数是C标准的一部分,因此也是C++的一部分。但如果你正在使用C++,我建议你使用观察者模式代替:http://en.wikipedia.org/wiki/Observer_pattern
/////////////////////////////////////////////////////////////////////
// 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);
}
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);
}
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;
};
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;
};