1 std::bind

std::bind 可以用来绑定一个函数 std::placeholders; 定义有_1_2_3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <functional>
using namespace std;
using namespace std::placeholders;

int f(int, char, double);
int main()
{
    // 翻转参数顺序
    auto frev = bind(f, _3, _2, _1);
    int x = frev(1.2, 'w', 7);
    cout<<x<<endl;
    return 0;
}
int f(int a, char b , double c)
{
    cout<<"a=="<< a <<",b==" <<b << ",c=="<<c <<endl;
    return  0;
}

2 std::function

std::function 可以用来定义一个函数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
int add(int a, int b){
    return a+b;
}
auto mod=[](int a, int b){return a%b;};

struct divide{
    int operator()(int m, int n){
        return m/n;
    }
};


int main()
{
    function<int(int,int)> func1= add;
    function<int(int,int)> func2= mod;
    function<int(int,int)> func3= divide();
    cout<<func1(5, 6)<<endl;
    cout<<func2(5, 6)<<endl;
    cout<<func3(5, 6)<<endl;
    return 0;
}