C++11中的function和bind

来源:互联网 发布:windows查看本机端口 编辑:程序博客网 时间:2024/06/06 04:03
     在C++11中添加了两个函数绑定模板, 即function和bind。function模板类和bind模板函数,使用它们可以实现类似函数指针的功能,但却比函数指针更加灵活,特别是函数指向类的非静态成员函数时。

         std::function和std::bind都可以绑定到普通函数(包括类的静态函数)、类的成员函数 。

下面给出简单的示例 :

////  main.cpp//  Cpp11StdBind////  Created by mrsimple on 4/12/14.//  Copyright (c) 2014 mrsimple. All rights reserved.//#include <iostream>#include <string>#include <functional>using namespace std;// 用于普通函数和类的静态成员函数typedef function<void (int)> mdPoint;// 普通函数void printNum(int num){    cout<<__func__<<", the num is "<<num<<endl;}// classclass ThreadPool{public:    ThreadPool() { cout << "max size : " << max_size<<endl; }    ~ThreadPool() {}    // 静态函数    static void setThreadPoolMaxSize(int size) {        max_size = size ;        cout<<__func__<<", set thread pool size , " <<size<<endl;    }        // 非静态成员函数    void setCoreThread(int core) {        core_size = core ;        cout<<__func__<<", core size , " <<core<<endl;    }    void outputCoreSize()    {        cout<<__func__<<", core size "<<core_size<<endl;    }        // 使用bind来绑定回调函数    void bindCallback()    {        mdPoint mp = bind(&ThreadPool::setCoreThread, this, placeholders::_1) ;        mp(10);    }public:   static int max_size;    // 非静态成员变量, 可以直接初始化数据    int core_size = 5;} ;// 定义静态成员变量int ThreadPool::max_size = 100 ;// mainint main(int argc, const char * argv[]){    cout<<ThreadPool::max_size<<endl;        // 使用function来绑定函数指针    mdPoint mp = (&printNum);    mp(123);        // 指向类的静态函数    mp = (&ThreadPool::setThreadPoolMaxSize);    mp(456);        auto tp = new ThreadPool();    tp->bindCallback() ;        // 带参数    auto cb2 = bind(&ThreadPool::setCoreThread, tp, placeholders::_1) ;    cb2(66);    // 使用bind来设置回调函数, 不带参数的    auto callback = bind(&ThreadPool::outputCoreSize, tp) ;    callback();        // lambda的bind    auto lmd = bind([] { cout<<"this is lambda."<<endl;}) ;    lmd();        // 传递参数    auto lmdp = bind([](string name) { cout <<name<<endl; }, placeholders::_1) ;    lmdp("mr.simple");        // 在placeholders位置上设置参数    auto lmdp2 = bind([](string name) { cout << "new name " <<name<<endl; } , "MR.SIMPLE -- NEW .");    lmdp2();    return 0;}

function的回调类的成员函数:

#include <iostream>#include <functional>using namespace std;//class View{public:    void onClick(int x, int y)    {        cout<<"X : "<<x<<", Y : "<<y<<endl;    }} ;// 定义function类型, 三个参数function<void (View*, int, int)> clickCallback ;// 普通函数function<int (int, int)> f ;//int add(int a, int b) {    return a + b ;}//int main(int argc, const char * argv[]){    View button ;    // 指向成员函数    clickCallback = &View::onClick ;    // 进行调用    clickCallback(&button, 10, 123);        f = add ;    cout<<"result : "<<f(4,5)<<endl;    return 0;}



0 0