首先看一下下面幾個輔助函數和結構體,它們是bind1st和bind2nd的基礎
1.unary_function
這個結構體負責對一元函數的描述:

unary_function
1 template <class _Arg, class _Result>
2 struct unary_function
3 {
4 typedef _Arg argument_type; ///< @c argument_type is the type of the
5 /// argument (no surprises here)
6
7 typedef _Result result_type; ///< @c result_type is the return type
8 };
2.binary_function
這個結構體負責對二元函數的描述:

binary_function
1 template <class _Arg1, class _Arg2, class _Result>
2 struct binary_function
3 {
4 typedef _Arg1 first_argument_type; ///< the type of the first argument
5 /// (no surprises here)
6
7 typedef _Arg2 second_argument_type; ///< the type of the second argument
8 typedef _Result result_type; ///< type of the return type
9 };
3.binder1st類

binder1st
1 template <class _Operation>
2 class binder1st
3 : public unary_function < typename _Operation::second_argument_type,
4 typename _Operation::result_type >
5 {
6 protected:
7 _Operation op;
8 typename _Operation::first_argument_type value;
9 public:
10 binder1st( const _Operation& __x,
11 const typename _Operation::first_argument_type& __y )
12 : op( __x ), value( __y ) {}
13
14 typename _Operation::result_type
15 operator()( const typename _Operation::second_argument_type& __x ) const
16 { return op( value, __x ); }
17
18 // _GLIBCXX_RESOLVE_LIB_DEFECTS
19 // 109. Missing binders for non-const sequence elements
20 typename _Operation::result_type
21 operator()( typename _Operation::second_argument_type& __x ) const
22 { return op( value, __x ); }
23 };
注意7~8行的op和value,分別用來保存綁定的函數操作和值。而在14~16行,可以看到這里直接使用op來處理value和__x參數。
從這兩段代碼可以看到,binder1st可以把二元函數間接變成一元函數(通過binder1st的operator()調用)。另外,14~15行的result_type、
second_argument_type和first_argument_type也意味著,如果我們自己要寫一個可以由bind1st綁定的函數,那么最好是先從unary_function
和binary_function結構體中繼承相應的traits,然后再實現operator()函數。
4.bind1st
bind1st函數實質上就是返回了一個binder1st類對象,注意看下面第7行代碼:

bind1st
1 /// One of the @link s20_3_6_binder binder functors@endlink.
2 template <class _Operation, class _Tp>
3 inline binder1st<_Operation>
4 bind1st( const _Operation& __fn, const _Tp& __x )
5 {
6 typedef typename _Operation::first_argument_type _Arg1_type;
7 return binder1st<_Operation>( __fn, _Arg1_type( __x ) );
8 }
5.binder2nd和bind2nd
與binder1st和bind1st類似,只是使用Op調用的參數位置發生了變化而已