配接器compose_f_gx,compose_f_gx_hy实现实例

2015-01-24 06:10:28 · 作者: · 浏览: 3

源码:?
template?
class compose_f_gx_hy_t?
??? :public binary_function ??? 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?
inline compose_f_gx_hy_t?
??? compose_f_gx_hy( const OP1& o1,const OP2& o2,const OP3& o3 )?
{?
??? return compose_f_gx_hy_t( 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(),ptr_fun(::toupper),ptr_fun(::toupper)) );?
??? copy( sub.begin(),sub.end(),ostream_iterator( cout,"" ) );?
??? system( "pause" );?
??? return 0;?
}?
说明:?
◆ 函数实现的是f(g(x))形式.?
??? ◆compose_f_gx_t继承自unary_function其实现为:templatestruct unary_function{// base class for unary functionstypedef _Arg argument_type;typedef _Result result_type;};?
??????? ◆ 注意最后在调用的时候是调用函数模板compose_f_gx.之所以调用这个函数而非直接调用compose_f_gx_t仿函数,原因是std::binder2nd >是一个数值,而非类型.经过函数的转换之后就能通过编译器了.?
??????????? 有了这个compose_f_gx_t,compose_f_gx_hx_t就很容易了.另外需要注意的是:如果是使用后者,则提供的第一个参数必须是两个参数的函数.?
?
下面是二元组合函数配接器示例:?
??????? template?
??????? class compose_f_gx_hy_t?
??????????? :public binary_function ??????????? 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?
??????? inline compose_f_gx_hy_t?
??????????? compose_f_gx_hy( const OP1& o1,const OP2& o2,const OP3& o3 )?
??????? {?
??????????? return compose_f_gx_hy_t( 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(),ptr_fun(::toupper),ptr_fun(::toupper)) );?
??????????? copy( sub.begin(),sub.end(),ostream_iterator( cout,"" ) );?
??????????? system( "pause" );?
??????????? return 0;?
??????? }?



摘自 yuanweihuayan的专栏