std::function

 

类模版std::function是一种通用、多态的函数封装。
可调用对象的包装器,它最重要的功能是实现延时调用。
std::function对象是对C++中现有的可调用实体的一种类型安全的封装。

 

1、绑定普通函数
void func(void)
{
    std::cout << __FUNCTION__ << std::endl;
}

std::function<void(void)> fr1 = func;
fr1();

 

2、绑定一个类的静态成员函数
class Foo
{
public:
    static int foo_func(int a)
    {
        std::cout << __FUNCTION__ << "(" << a << ") ->: ";
        return a;
    }
};
std::function<int(int)> fr2 = Foo::foo_func;
std::cout << fr2(123) << std::endl;

 

3、重载()函数
class Bar
{
public:
    int operator()(int a)
    {
        std::cout << __FUNCTION__ << "(" << a << ") ->: ";
        return a;
    }
};
Bar bar;
std::cout << bar(123) << std::endl;

 

4、回调函数
void call_when_even(int x, const std::function<void(int)> & f)
{
    if (!(x & 1))  //x % 2 == 0
    {
        f(x);
    }
}
void output(int x)
{
    std::cout << x << " ";
}
call_when_even(i, output);

 

posted @ 2019-06-25 23:36  osbreak  阅读(292)  评论(0编辑  收藏  举报