函数子即函数对象。
如下所示:
class Widget
{
public:
bool IsBigVal();
int GetValue();
...
}
struct IsInteresting
{
bool operator() (const Widget& one)
{
return one.IsBigValue();
}
}
在一个存储Widget的vector中找到第一个感兴趣的元素,可以这样做:
std::vector<Widget> datas;
...
auto iter = std::find_if(data.begin(), datas.end(), IsInteresting);
if (iter != datas.end())
{
...
}
如果你想找到第一个不感兴趣的元素:预期的做法是:
std::vector<Widget> datas;
...
auto iter = std::find_if(data.begin(), datas.end(), std::not1(IsInteresting));
if (iter != datas.end())
{
...
}
这种做法不能通过编译,原因是IsInteresting不可配接。
在STL中,除了not1
,其他的函数配接器如not2
、bind1st
、bind2st
都要求可配接的函数子。
什么是可配接函数子?
可配接函数子能够提供一些类型定义,如argument_type、first_argument_type、second_argument_type、result_type等。
函数子如何变成可配接的?
直接继承自类unary_function
、binary_function
即可。
- 对于一元判别式函数子,继承自unary_function;
- 对于二元判别式函数子,继承自binary_function;
一元函数子继承unary_function
时需要提供2个类型实参,operator()的参数类型Widget及其返回类型bool。
struct IsInteresting : public std::unary_function<Widget, bool>
{
bool operator() (const Widget& one)
{
return one.IsBigValue();
}
}
二元函数子继承binary_function
需要提供3个类型实参,operator()的两个参数类型及其返回类型bool。
struct IsLessWidget : public std::binary_function<Widget, Widget, bool>
{
bool operator () (const Widget& one, const Widget& other)
{
return one.GetValue() < other.GetValue();
}
}
不管是一元还是二元函数子,如果operator()的参数类型是指针,那么继承时传入的类型需要和operator的参数类型一致。
(其他情况直接传参数类型即可)
以上面的IsLessWidget为例:
struct IsLessWidget : public std::binary_function<const Widget*, const Widget*, bool>
{
bool operator () (const Widget* one, const Wigget* other)
{
return one->GetValue() < other->GetValue();
}
}