测试代码:
cpp
#include <iostream>
#include <functional>
int addFunc(int a, int b) {
return a + b;
}
void testFunction() {
// 声明一个function,接受俩个int参数,返回int数据
std::function<int(int, int)> func;
// 绑定不同的可调用对象
// 普通函数
func = addFunc;
cout << "9526 + 1 :" << func(9526, 1) << endl;
// lambda表达式
func = [](int a, int b) { return a - b;};
cout << "9528 - 1 :" << func(9528, 1) << endl;
// 成员函数
class Calculator {
public:
int sub(int a, int b) { return a - b; }
static int staticFuncAdd(int a, int b) { return a + b; }
};
Calculator calc;
// 绑定对象和成员函数
func = std::bind(&Calculator::sub, &calc, std::placeholders::_1, std::placeholders::_2);
cout << "0 - 1 = " << func(0, 1) << endl;
// 绑定静态成员函数
func = &Calculator::staticFuncAdd;
cout << "1 + 1 = " << func(1, 1) << endl;
//仿函数
class Divider {
public:
int operator()(int a, int b) {
return a / b;
}
};
Divider div;
func = div;
cout << "10 / 3 = " << func(10, 3) << endl;
}
打印:

ok