您好,欢迎来到伴沃教育。
搜索
您的当前位置:首页C++11 std::function 和 std::bind

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

来源:伴沃教育

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

Copyright © 2019- bangwoyixia.com 版权所有 湘ICP备2023022004号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务