1

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

 1 year ago
source link: https://forrestsu.github.io/posts/cpp/cpp11-std_function%E5%92%8Cstd_bind/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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

2017年6月9日
| 字数 871
| CPP

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK