c++11-std::functionbind
std::function
可調用對象如下:
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);
?
?
?
?
}
總結
以上是生活随笔為你收集整理的c++11-std::functionbind的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++11-Varadic Templa
- 下一篇: c++11-type_traits类型萃