Using std :: function bindings
The following source content from the "in-depth application C ++ 11 code optimization and engineering application" 1.5.2 callable wrapper --std :: function
std :: function is callable wrapper. It is a template class can accommodate all calls except class member objects (function) of the pointer. Template by specifying its parameters, which can be treated in a uniform way function , function objects , function pointers , and allows saving and delay execution thereof.
#include <iostream>
#include <functional>
using namespace std;
// 普通函数
void func(void)
{
cout << __FUNCTION__ << endl;
}
// 静态函数
struct Foo
{
static int foo_func(int a)
{
cout << __FUNCTION__ << "(" << a << ")->:";
return a;
}
};
// 仿函数
struct Bar
{
int operator()(int a)
{
std::cout << __FUNCTION__ << "(" << a << ") ->: ";
return a;
}
};
int main()
{
// 绑定一个普通函数
std::function<void(void)> fr1 = func;
fr1();
// 绑定一个类的静态成员函数
std::function<int(int)> fr2 = Foo::foo_func;
std::cout << fr2(123) << std::endl;
// 绑定一个仿函数
Bar bar;
fr2 = bar;
std::cout << fr2(234) << std::endl;
return 0;
}