std::function
可调用对象如下:
- 是一个函数指针
- 一个具有operator()成员函数的类对象
- 一个可被转换为函数指针的类对象
- 是一个类成员指针
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);
}