std::bind 用于绑定一个函数,返回另外一种调用方式的函数对象 ,可以改变参数顺序 和个数
std::function 用于构建一个函数特别是 回调函数 ,用于替代 函数指针/*常和匿名函数一起用回调*/
参考以下代码
#include<iostream>
#include "functional"
using namespace std;
double calculate(double x, double y, char op)
{
switch (op)
{
case '+':
{
return x + y;
}break;
case '-':
{
return x - y;
}break;
}
return 0;
}
int main()
{
//bind
auto plus = std::bind(calculate, std::placeholders::_1, std::placeholders::_2, '+');/*calculate 参数1 参数2*/
auto sub = std::bind(calculate, std::placeholders::_2, std::placeholders::_1, '-');/*calculate 参数2 参数1*/
cout << plus(5, 2) << endl;
cout << sub(5, 2) << endl;/*调用时候 5为 calculate的第二个参数*/
//function
typedef std::function<double(double , double , char)> func;
func fun = calculate;
cout << fun(1, 2, '+') << endl;;
//function ptr
double (*p)(double, double, char) =calculate;
cout << p(1, 1, '+') << endl;;
//function + bind
std::function<double (double , double )> plus_2;
plus_2 = plus;
cout << plus_2(2, 3) << endl;;
system("pause");
return 0;
}