boost::bind 與 boost::function 的使用方法例子

原文地址:https://yq.aliyun.com/articles/33187

 

 

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
 
using namespace boost;
using namespace std;
 
int f(int a, int b)
{
    return a + b;
}
 
int g(int a, int b, int c)
{
    return a + b * c;
}
 
class Point
{
public:
    Point(int x, int y) : _x(x), _y(y) {}
    void print(const char *msg) {
        cout << msg << "x=" << _x << ", y=" << _y << endl;
    }
private:
    int _x, _y;
};
 
int main()
{
    //! f 有多少個參數,f 後面就要跟多少個參數。如果不明確的,用佔位符
    cout << bind(f, 2, 3)() << endl;    // ==> f(2, 3)
    cout << bind(f, 12, _1) (5) << endl;   // ==> f(12, 5),其中參數b爲不明確參數
    cout << bind(g, _2, _1, 3) (3, 5) << endl;  // ==> g(5, 3, 3) 注意順序
 
    Point p(11, 34);
    Point &rp = p;
    Point *pp = &p;
 
    bind(&Point::print, p, "Point: ") ();
    //   ^              ^
    // 注意,爲表示Point::print爲成員函數,成員函數前面要加&區分。
    // 對象可以爲實例、引用、指針
    bind(&Point::print, rp, "Reference: ") ();  //! 引用
    bind(&Point::print, pp, _1) ("Pointer: ");  //! 指針
    bind(&Point::print, _1, _2) (p, "As parameter: ");  //! 對象也可以用佔位符暫時代替
 
    //! function的類型定義與需要的參數有關
    function<void ()> func0 = bind(&Point::print, p, "func0: ");
    function<void (const char *)> func1 = bind(&Point::print, pp, _1);
 
    func0();    //! function對象的調用
    func1("func1: ");
 
    return 0;
}

 

一般情況下,bind 與 function 配合使用。

bind與function還可以將類型完成不同的函數(成員函數與非成員函數)包裝成統一的函數調用接口。如下示例:

 

#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <iostream>
#include <vector>
 
using namespace boost;
using namespace std;
 
class Point
{
public:
    Point(int x, int y) : _x(x), _y(y) {}
    void print(string msg) {
        cout << msg << "x=" << _x << ", y=" << _y << endl;
    }
private:
    int _x, _y;
};
 
class Person
{
public:
    Person(string name, int age) : _name(name), _age(age) {}
    void sayHello() {
        cout << "Hello, my name is " << _name << ", my age is : " << _age << endl;
    }
private:
    string _name;
    int _age;
};
 
void printSum(int limit)
{
    int sum = 0;
    for (int i = 0; i < limit; ++i) {
        sum += i;
    }
    cout << "sum = " << sum << endl;
}
 
void doAll(vector<function<void ()> > &funcs)
{
    for (size_t i = 0; i < funcs.size(); ++i) {
        funcs[i] ();
    }
}
 
int main()
{
    vector<function<void ()> > funcList;
 
    Person john("John", 23);
    funcList.push_back(bind(&Person::sayHello, john));
 
    Point p1(23, 19);
    funcList.push_back(bind(&Point::print, p1, "Point: "));
 
    funcList.push_back(bind(printSum, 20));
 
    doAll(funcList);
    return 0;
}

 

3、局部靜態函數

void Test()

{

 static Test

{

           static void funRun(int iData)

          {

               

          }

}

 function<void()> fun = boost::bind(&Test::funRun,10);

fun();

 

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章