Bind2nd源码解析

例:transform(coll1.begin(), coll1.end(), back_inserter(coll2), bind2nd(multiplies<int>(), 10));


1、调用模板函数bind2nd,第一个参数为multiplies<int>临时对象。

// TEMPLATE FUNCTION bind2nd
template<class _Fn2,
	class _Ty> inline
	binder2nd<_Fn2> bind2nd(const _Fn2& _Func, const _Ty& _Right)
	{	// return a binder2nd functor adapter
	typename _Fn2::second_argument_type _Val(_Right);//此处将仿函数multiplies<int>临时对象的第二个参数设置为10
	return (_STD binder2nd<_Fn2>(_Func, _Val));  //返回模板类binder2nd临时对象
	}

2、模板类binder2nd的定义:

// TEMPLATE CLASS binder2nd
template<class _Fn2>
	class binder2nd
		: public unary_function<typename _Fn2::first_argument_type,
			typename _Fn2::result_type>   //设置参数类型和返回值类型
	{	// functor adapter _Func(left, stored)
public:
	typedef unary_function<typename _Fn2::first_argument_type,
		typename _Fn2::result_type> _Base;
	typedef typename _Base::argument_type argument_type;
	typedef typename _Base::result_type result_type;

	binder2nd(const _Fn2& _Func,
		const typename _Fn2::second_argument_type& _Right)  //构造函数,仿函数第二个参数被赋值
		: op(_Func), value(_Right)
		{	// construct from functor and right operand
		}

	result_type operator()(const argument_type& _Left) const  //调用仿函数
		{	// apply functor to operands
		return (op(_Left, value));
		}

	result_type operator()(argument_type& _Left) const
		{	// apply functor to operands
		return (op(_Left, value));
		}

protected:
	_Fn2 op;	// the functor to apply
	typename _Fn2::second_argument_type value;	// the right operand
	};

3、模板类binder2nd模板基类unary_function的定义:

// FUNCTIONAL STUFF (from <functional>)
// TEMPLATE STRUCT unary_function
template<class _Arg,class _Result>
	struct unary_function
	{	// base class for unary functions
	typedef _Arg argument_type;
	typedef _Result result_type;
	};


Bind2nd模板函数返回一个Binder2nd临时对象,该对象也是个函数对象,在算法transform调用Binder2nd仿函数时,Binder2nd调用第一个参数指定的函数对象。


算法transform的源码:

 // TEMPLATE FUNCTION transform WITH UNARY OP  //只是其中一个定义
template<class _InIt,
 class _OutIt,
 class _Fn1> inline
 _OutIt _Transform(_InIt _First, _InIt _Last,
  _OutIt _Dest, _Fn1 _Func)
 { // transform [_First, _Last) with _Func
 for (; _First != _Last; ++_First, ++_Dest)
  *_Dest = _Func(*_First);  //调用Binder2nd函数对象,将第一个参数传递进去,第二个参数在生成临时对象时赋值.
 return (_Dest);
 }








原文地址:https://www.cnblogs.com/ggzone/p/4052441.html