配接器compose_f_gx,compose_f_gx_hy实现实例

41 篇文章 0 订阅
39 篇文章 2 订阅

源码:
template<class OP1,class OP2,class OP3>
class compose_f_gx_hy_t
	:public binary_function<typename OP2::argument_type,
	typename OP3::argument_type,
	typename OP1::result_type>
{
private:
	OP1 op1;
	OP2 op2;
	OP3 op3;
public:
	compose_f_gx_hy_t( const OP1& o1,const OP2& o2,const OP3& o3 ):op1( o1 ),op2( o2 ),op3(o3){}
	typename OP1::result_type 
		operator()( const typename OP2::argument_type& x,const typename OP3::argument_type& y ) const
	{
		return op1( op2(x),op3(y) );
	}
};
template<class OP1,class OP2,class OP3>
inline compose_f_gx_hy_t<OP1,OP2,OP3>
	compose_f_gx_hy( const OP1& o1,const OP2& o2,const OP3& o3 )
{
	return compose_f_gx_hy_t<OP1,OP2,OP3>( o1,o2,o3 );
}
int main()
{
	string s("Internationalization");
	string sub( "Nation" );

	string::iterator pos = search( s.begin(),s.end(),sub.begin(),sub.end(),
		compose_f_gx_hy( equal_to<int>(),ptr_fun(::toupper),ptr_fun(::toupper)) );
	copy( sub.begin(),sub.end(),ostream_iterator<char>( cout,"" ) );
	system( "pause" );
	return 0;
}
说明:
◆ 函数实现的是f(g(x))形式.
	◆compose_f_gx_t继承自unary_function<typename OP2::argument_type,typename OP1::result_type>其实现为:template<class _Arg,class _Result>struct unary_function{// base class for unary functionstypedef _Arg argument_type;typedef _Result result_type;};
		◆ 注意最后在调用的时候是调用函数模板compose_f_gx.之所以调用这个函数而非直接调用compose_f_gx_t仿函数,原因是std::binder2nd<std::multiplies<int> >是一个数值,而非类型.经过函数的转换之后就能通过编译器了.
			有了这个compose_f_gx_t,compose_f_gx_hx_t就很容易了.另外需要注意的是:如果是使用后者,则提供的第一个参数必须是两个参数的函数.

下面是二元组合函数配接器示例:
		template<class OP1,class OP2,class OP3>
		class compose_f_gx_hy_t
			:public binary_function<typename OP2::argument_type,
			typename OP3::argument_type,
			typename OP1::result_type>
		{
		private:
			OP1 op1;
			OP2 op2;
			OP3 op3;
		public:
			compose_f_gx_hy_t( const OP1& o1,const OP2& o2,const OP3& o3 ):op1( o1 ),op2( o2 ),op3(o3){}
			typename OP1::result_type 
				operator()( const typename OP2::argument_type& x,const typename OP3::argument_type& y ) const
			{
				return op1( op2(x),op3(y) );
			}
		};
		template<class OP1,class OP2,class OP3>
		inline compose_f_gx_hy_t<OP1,OP2,OP3>
			compose_f_gx_hy( const OP1& o1,const OP2& o2,const OP3& o3 )
		{
			return compose_f_gx_hy_t<OP1,OP2,OP3>( o1,o2,o3 );
		}
		int main()
		{
			string s("Internationalization");
			string sub( "Nation" );

			string::iterator pos = search( s.begin(),s.end(),sub.begin(),sub.end(),
				compose_f_gx_hy( equal_to<int>(),ptr_fun(::toupper),ptr_fun(::toupper)) );
			copy( sub.begin(),sub.end(),ostream_iterator<char>( cout,"" ) );
			system( "pause" );
			return 0;
		}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值