《C++11新特性之std::function》提到了std::function作为回调函数。
今天主要讨论不同情况下std::function作为回调使用。
使用回调
#include <functional>
#include <iostream>
namespace {
using cb1_t = std::function<void()>;
using cb2_t = std::function<void(int)>;
void foo1()
{
std::cout << "foo1 is called\n";
}
void foo2(int i)
{
std::cout << "foo2 is called with: " << i << "\n";
}
struct S {
void foo3()
{
std::cout << "foo3 is called.\n";
}
};
}
int main()
{
// Bind a free function.
cb1_t f1 = std::bind(&foo1);
// Invoke the function foo1.
f1();
// Bind a free function with an int argument.
// Note that the argument can be specified with bind directly.
cb1_t f2 = std::bind(&foo2, 5);
// Invoke the function foo2.
f2();