wrapper 函数 bind 和 function 使用实例

#include <random>
#include <iostream>
#include <functional>
 
void f(int n1, int n2, int n3, const int& n4, int n5)
{
    std::cout << n1 << ' ' << n2 << ' ' << n3 << ' ' << n4 << ' ' << n5 << '\n';
}
 
int g(int n1)
{
    return n1;
}
 
struct Foo {
    void print_sum(int n1, int n2)
    {
        std::cout << n1+n2 << '\n';
    }
};
 
int main()
{
    using namespace std::placeholders;
 
    // demonstrates argument reordering and pass-by-reference
    int n = 7;
    auto f1 = std::bind(f, _2, _1, 42, std::cref(n), n);//注:cref 的意思是常量引用,也就是说不能改变该引用,也可以直接使用ref()则可以改变
    n = 10;
    f1(1, 2, 1001); // 1 is bound by _1, 2 is bound by _2, 1001 is unused
 
    // nested bind subexpressions share the placeholders
    auto f2 = std::bind(f, _3, std::bind(g, _3), _3, 4, 5);
    f2(10, 11, 12);
 
 
    // bind to a member function
    Foo foo;
    auto f3 = std::bind(&Foo::print_sum, foo, 95, _1);
    f3(5);
}

运行结果:

C:\Windows\system32\cmd.exe /c bind.exe
2 1 42 10 7
12 12 12 4 5
100
Hit any key to close this window...

说明:bind 函数里面的"_n"代表的是占位符,在实际调用函数之前表示这里有一个参数;在绑定一个类的成员函数的时候需要指明类成员函数的隐含指针“this”,因此最后一个bind 后面会有一个“foo”参数。

#include <functional>
#include <iostream> struct Foo { Foo(int num) : num_(num) {} void print_add(int i) const { std::cout << num_+i << '\n'; } int num_;}; void print_num(int i){ std::cout << i << '\n';} int main(){ // store a free function std::function<void(int)> f_display = print_num; f_display(-9); // store a lambda std::function<void()> f_display_42 = []() { print_num(42); }; f_display_42(); // store the result of a call to std::bind std::function<void()> f_display_31337 = std::bind(print_num, 31337); f_display_31337(); // store a call to a member function std::function<void(const Foo&, int)> f_add_display = &Foo::print_add; Foo foo(314159); f_add_display(foo, 1);}

运行结果:

C:\Windows\system32\cmd.exe /c function.exe
-9
42
31337
314160
Hit any key to close this window...

说明:function<> 尖括号内部用于表示函数返回值和参数(参数放在‘()’中)。

原文地址:https://www.cnblogs.com/zhuyp1015/p/2634326.html