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

 

转载于:https://www.cnblogs.com/osbreak/p/11087398.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值