std::bind使用

#include <iostream>
#include <functional>
 
void fn(int n1, int n2, int n3) {
    std::cout << n1 << " " << n2 << " " << n3 << std::endl;
}
 
int fn2() {
    std::cout << "fn2 has called.\n";
    return -1;
}
 
int main()
{
    using namespace std::placeholders;
    auto bind_test1 = std::bind(fn, 1, 2, 3);
    auto bind_test2 = std::bind(fn, _1, _2, _3);
    auto bind_test3 = std::bind(fn, 0, _1, _2);
    auto bind_test4 = std::bind(fn, _2, 0, _1);
 
    bind_test1();//輸出1 2 3
    bind_test2(3, 8, 24);//輸出3 8 24
    bind_test2(1, 2, 3, 4, 5);//輸出1 2 3,4和5會被丟棄
    bind_test3(10, 24);//輸出0 10 24
    bind_test3(10, fn2());//輸出0 10 -1
    bind_test3(10, 24, fn2());//輸出0 10 24,fn2會被調(diào)用,但其返回值會被丟棄
    bind_test4(10, 24);//輸出24 0 10
    return 0;
}

輸出:

1 2 3
3 8 24
1 2 3
0 10 24
fn2 has called.
0 10 -1
fn2 has called.
0 10 24
24 0 10

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容