C++代码阅读之boost::function与回调函数

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_28455067/article/details/81611786

参考资料:
1、陈帅陪马大大为软件献青春的博客
2、benny5609的专栏
3、sld666666

boost::function

一、介绍
Boost.Function库包含了一个类族的函数对象的包装。它的概念很像广义上的回调函数。其有着和函数指针相同的特性但是又包含了一个调用的接口。一个函数指针能够在能以地方被调用或者作为一个回调函数。boost.function能够代替函数指针并提供更大的灵活性。
利用 boost::function 存储 普通函数、类成员函数、函数对象,实现函数回调的功能。

二、使用

//形式:首选形式
boost::function<float(int x,int y)>f

2.1普通函数

int fsum(int i, int j)
{
    return i + j;
}
class Person
{
public:
    void operator() (std::string name, int age)
    {
        std::cout << name << ": " << age << std::endl;
    }
};

class Car
{
public:
    Car(){}
    virtual ~Car(){}
    void info(int i)
    {
        std::cout << "info = " << i << std::endl;
    }
};

/*************************************/ 
void test_function()
{
    // 1. 普通函数
    boost::function<int(int, int)> func1;
    func1 = fsum;
    std::cout << "4 + 5 = " << func1(4, 5) << std::endl;
}

这里的function就相当于函数的对象调用。

2.2 函数对象

// 2. 函数对象
    boost::function<void(std::string, int)> func2;
    Person person;
    func2 = person;
    func2("myname", 30);

2.3成员函数


// 3. 成员函数
    boost::function<void(Car*, int)> func3;
    func3 = &Car::info;
    Car car;
    func3(&car, 25);

2.4空函数

// 4. 空函数
    boost::function<int(int, int)> func4;
    assert(func4.empty());
    assert(!func1.empty());
    func1.clear();
    assert(func1.empty());
    try
    {
        func1(4, 5);
    }
    catch (std::exception& e)
    {
        std::cout << e.what() << std::endl;
    }

三、典型例子

 void print(int a) 
{ 
    cout << a << endl; 
}
typedef boost::function<void (int)> SuccessPrint;
int _tmain(int argc, _TCHAR* argv[]) 
{ 
    vector<SuccessPrint> printList;
    SuccessPrint printOne = boost::bind(print, _1); 
     printList.push_back(printOne); 
    SuccessPrint printTwo = boost::bind(print, _1); 
    printList.push_back(printTwo); 
    SuccessPrint printThree = boost::bind(print, _1); 
    printList.push_back(printTwo); 
    // do something else
    for (int i = 0; i < printList.size(); ++i) 
        printList.at(i)(i);
    return 0; 
}
比如当程序执行到某一处的时候想绑定某一个函数, 但是不想立即执行, 我们就可以声明一个函数对象,给此对象绑定相应的函数, 做一些其他事情,然后再来执行绑定的函数,     上述代码中首先把声明一个函数对象 typedef boost::function<void (int)> SuccessPrint, 然后把print绑定到斥对象中, 放入vector中, 到最后才来执行这print()函数。

PS:

boost::bind介绍

待续:

猜你喜欢

转载自blog.csdn.net/baidu_28455067/article/details/81611786