40. 若一个类是函数子,则应该使它可配接

函数子即函数对象。

如下所示:

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,其他的函数配接器not2bind1stbind2st都要求可配接的函数子。

什么是可配接函数子?
可配接函数子能够提供一些类型定义,如argument_type、first_argument_type、second_argument_type、result_type等。

函数子如何变成可配接的?
直接继承自类unary_functionbinary_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();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值