c++ std::bind用法小结。

来源:互联网 发布:家庭资产负债表 知乎 编辑:程序博客网 时间:2024/06/05 03:29

有些新东西,虽然不怎么使用这一套,但经常碰到,还是要了解一下。
小小试验,总结与分享:

#include<functional>#include<iostream>using namespace std;class Cat{public:    Cat()     {        //001使用内部绑定;        std::bind(&Cat::cry, this)();      }    void cry()     {        cout << "this is a cat" << endl;    }    void cry2()    {        cout << "I'm missing fishes" << endl;    }};void print1(){    cout <<"print hello" << endl;}void print2(int a){    cout <<"print "<< a << endl;}int selectMax(int a, int b){    return a > b ? a : b;}void square(int num){    cout <<"result:"<< num*num << endl;}int main(){    Cat c1;    //002使用外部绑定;    std::bind(&Cat::cry2, &c1)();    //003不带参数;    std::bind(print1)();    //004带参数;    std::bind(print2, std::placeholders::_1)(12);    //005多重绑定    auto selectMaxAndSquare = std::bind(square, std::bind(selectMax, std::placeholders::_1, std::placeholders::_2));    selectMaxAndSquare(3, 6);    system("pause");    return 0;}
0 0