boost::function介绍

1. 介绍
    Boost.Function库包含了一个类族的函数对象的包装。它的概念很像广义上的回调函数。其有着和函数指针相同的特性但是又包含了一个调用的接口。一个函数指针能够在能以地方被调用或者作为一个回调函数。boost.function能够代替函数指针并提供更大的灵活性。
2. 使用
    Boost.Function有两种形式:boost::function<float(int x, int y)>f
    使用类型: 普通函数, 成员函数, 函数对象。
    使用function时,可以通过empty函数或与0比较来判断其是否指向一个有效的函数。如果function没有指向一个有效的函数,调用时会抛出bad_function_call的异常。function的clear函数可以使其不再关联到一个函数或函数对象,如果该function本身就是空的,调用该函数也不会带来任何问题。
3.例子

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;

    // 2. 函数对象

    boost::function<void(std::string, int)> func2;

    Person person;

    func2 = person;

    func2("myname", 30);

    // 3. 成员函数

    boost::function<void(Car*, int)> func3;

    func3 = &Car::info;

    Car car;

    func3(&car, 25);

    // 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;

    }

}

猜你喜欢

转载自blog.csdn.net/technologyleader/article/details/81706194