std c ++ 11's :: bind

Taken: https://www.jianshu.com/p/621fc81a1dc1
effect:
on A package callable entities (function pointer, functor, lambda expression), such packages can function pre-bound parameter.

Example of use:

#include <iostream>
using namespace std;

void global_func(int a){//全局函数
    cout<<"call global_func:"<<a<<endl;
}

auto labmda = [](int a){cout<<"lambda:"<<a<<endl;};

class ClassA{
public:
    void member_func(int a){//类成员函数
        cout<<"call ClassA::member_func:"<<a<<endl;
    }
    
    static void static_member_func(int a){//类静态函数
        cout<<"call ClassA::static_member_func:"<<a<<endl;
    }
};

class Functor{//仿函数
public:
    void operator()(int a){
        cout<<"call Functor()"<<a<<endl;
    }
};


int main(int argc, const char * argv[]) {
    function<void(int)> func;
    func = global_func;
    func(10);
    auto bindGlobalFunc = std::bind(global_func, 10);
    bindGlobalFunc();
    
    func = labmda;
    func(11);
    auto bindLabmdaFunc = std::bind(labmda, 11);
    bindLabmdaFunc();
    
    Functor testFunctor;
    func = testFunctor;
    func(12);
    auto bindFunctorFunc = std::bind(testFunctor, 12);
    bindFunctorFunc();
    
    ClassA a_object;
    func = std::bind(&ClassA::member_func, &a_object, std::placeholders::_1);
    func(13);
    auto bindClassMemberFunc = std::bind(&ClassA::member_func,&a_object, 13);
    bindClassMemberFunc();
    
    func = std::bind(&ClassA::static_member_func, std::placeholders::_1);
    func(14);
    auto bindClassStaticFunc = std::bind(&ClassA::static_member_func, 14);
    bindClassStaticFunc();
    return 0;
}

Output:

call global_func:10
call global_func:10
lambda:11
lambda:11
call Functor()12
call Functor()12
call ClassA::member_func:13,
call ClassA::member_func:13
call ClassA::static_member_func:14
call ClassA::static_member_func:14

Precautions:

In the form of parameters are passed by value pre-bound
parameters are not pre-bound to use std :: placeholders (placeholders) in the form of mass, from the beginning of _1, in ascending order, in the form passed by reference

std :: bind the return value is a callable entity can be directly assigned to std :: function

For the pointer bound reference type parameter, the caller needs to ensure that the life cycle there before calling

std :: placeholders represent the new callable object of several parameters of the original function of several parameters and match

Published 21 original articles · won praise 0 · Views 9502

Guess you like

Origin blog.csdn.net/qq_40230900/article/details/87091910