c++復習(六)--bind

3359 ワード

関数バインドbind関数は,ある形式のパラメータリストを既知の関数とバインドし,新しい関数を形成するために用いられ,bindは関数アダプタである.
    auto fun = [](int *array,int n,int num){
        for (int i=0; i<n; i++) {
            if (array[i]>num) {
                cout<<array[i]<<ends;
            }
            cout<<endl;
        }
    };

    int array[] = {1,3,5,7,9};
    auto func1 = bind(fun, _1,_2,5);
    func1(array,sizeof(array)/sizeof(*array));

bindで使用される一般的な形式:
    auto newfun = bind(fun,arg_list);//  fun     ,arg_list          。  newfun(),newfun()   fun(arg_list)。

bindの一般的な使い方1:関数パラメータの呼び出しを減らすのが最も一般的な使い方です.プレースホルダ:1,_2等、placeholderに位置決め、1は最初のパラメータです.2は2番目のパラメータで、このように押します!bindの一般的な使い方2:パラメータの呼び出し順序を変更します.
int fun(int a,int b);
auto newfound = bind(fun,_2,_1);//  newfound(1,2);     fun(2,1)

OKですが、ここで注意しなければならないのはクラスメンバー関数の使用です.
    class Myclass{
    public:
        void fun1(void){
            cout<<"void fun1(void)"<<endl;
        }
        int fun2(int i){
            cout<<"int fun2(int i) "<<"i="<<i<<endl;
            return i;
        }
    };

//  
    Myclass my;//       
    auto fun1 = bind(&Myclass::fun1, my);
    fun1();

    Myclass * p;
    auto fun2 = bind(&Myclass::fun2, p,_1);
    int i = fun2(1);
    cout<<"i="<<i<<endl;
//             this