c++11-std::function&bind

std::function

可调用对象如下:

  1. 是一个函数指针
  2. 一个具有operator()成员函数的类对象
  3. 一个可被转换为函数指针的类对象
  4. 是一个类成员指针

std::function是可调用对象包装器,是一个类模版,可以容纳除类成员函数指针外的所有可调用对象。

头文件是<functional>

void func(void)

{

}

class Foo

{

  public:

         static int foo_func(int a);

}

class Bar

{

public:

int operator()(int a);

}

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

std::function<int(int)> fr2=Foo::foo_func;

用途:

1.可以作为回调函数,作为函数的参数

call_when_even(int x, const std::function<void(int)>& f);

 

std::bind

std::bind可以把函数数的参数进行绑定,并把返回对象用std::function进行保存。

1.将可调用对象与其参数以前绑定为一个仿函数

2.将多元可调用对象转成一元或者(n-1)元可调用对象

auto fr=std::bind(output,std::placeholder::_1);

auto fr=std::bind(output,std::placeholder::_1,2)(1);

std::placeholder_1是一个占位符,代表这个位置将在函数调用的时候,被传入的第一个参数所替代。

1.使用binder简化和增强的bind1st,bind2nd

int count=std::count_if(coll.begin(),coll.end(),std::bind1st(less<int>(),10);

std::bind2nd(less<int>(),10);

2.使用组合bind函数

查找集合中大于5,小于10的元素个数

std::bind(std::greater<int>(),std::placeholders::_1,5);

using std::placeholders::_1;

auto f=std::bind(std::logical_and<bool>(),std::bind(std::greater<int>(),_1,5),std::bind(std::less_equal<int>(),_1,10);

int count=std::count_if(coll.begin(),coll.end(),f);

 

 

 

 

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值