美文网首页
C++11 std::function 和 std::bind

C++11 std::function 和 std::bind

作者: ColdRomantic | 来源:发表于2017-06-09 16:50 被阅读15次

1 std::bind

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

#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 可以用来定义一个函数

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;
}

相关文章

网友评论

      本文标题:C++11 std::function 和 std::bind

      本文链接:https://www.haomeiwen.com/subject/frjfqxtx.html