list2 通過繼承storage2來包含兩個成員a1_和a2_
[cpp]
struct logical_and;
struct logical_or;
template< class A1, class A2 > class list2: private storage2< A1, A2 >
{
private:
typedef storage2< A1, A2 > base_type;
public:
list2( A1 a1, A2 a2 ): base_type( a1, a2 ) {}
A1 operator[] (boost::arg<1>) const { return base_type::a1_; }
A2 operator[] (boost::arg<2>) const { return base_type::a2_; }
A1 operator[] (boost::arg<1> (*) ()) const { return base_type::a1_; }
A2 operator[] (boost::arg<2> (*) ()) const { return base_type::a2_; }
template<class T> T & operator[] (_bi::value<T> & v) const { return v.get(); }
template<class T> T const & operator[] (_bi::value<T> const & v) const { return v.get(); }
template<class T> T & operator[] (reference_wrapper<T> const & v) const { return v.get(); }
template<class R, class F, class L> typename result_traits<R, F>::type operator[] (bind_t<R, F, L> & b) const { return b.eval(*this); }
template<class R, class F, class L> typename result_traits<R, F>::type operator[] (bind_t<R, F, L> const & b) const { return b.eval(*this); }
template<class R, class F, class A> R operator()(type<R>, F & f, A & a, long)
{
return unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);
}
template<class R, class F, class A> R operator()(type<R>, F const & f, A & a, long) const
{
return unwrapper<F const>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);
}
template<class F, class A> void operator()(type<void>, F & f, A & a, int)
{
unwrapper<F>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);
}
template<class F, class A> void operator()(type<void>, F const & f, A & a, int) const
{
unwrapper<F const>::unwrap(f, 0)(a[base_type::a1_], a[base_type::a2_]);
}
template<class A> bool operator()( type<bool>, logical_and & /*f*/, A & a, int )
{
return a[ base_type::a1_ ] && a[ base_type::a2_ ];
}
template<class A> bool operator()( type<bool>, logical_and const & /*f*/, A & a, int ) const
{
return a[ base_type::a1_ ] && a[ base_type::a2_ ];
}
template<class A> bool operator()( type<bool>, logical_or & /*f*/, A & a, int )
{
return a[ base_type::a1_ ] || a[ base_type::a2_ ];
}
template<class A> bool operator()( type<bool>, logical_or const & /*f*/, A & a, int ) const
{
return a[ base_type::a1_ ] || a[ base_type::a2_ ];
}
template<class V> void accept(V & v) const
{
base_type::accept(v);
}
bool operator==(list2 const & rhs) const
{
return ref_compare(base_type::a1_, rhs.a1_, 0) && ref_compare(base_type::a2_, rhs.a2_, 0);
}
};
代碼一上來定義了兩個空的類,表示邏輯與和或。
下面四個函數比list1要多點:
[cpp]
A1 operator[] (boost::arg<1>) const { return base_type::a1_; }
A2 operator[] (boost::arg<2>) const { return base_type::a2_; }
A1 operator[] (boost::arg<1> (*) ()) const { return base_type::a1_; }
A2 operator[] (boost::arg<2> (*) ()) const { return base_type::a2_; }
其他的list3-list9也類似。
總結:listN模板通過繼承storageN模板,獲得了保存對應數目的占位符的能力。並提供了數組操作符operator[]()來獲取這些占位符對象,同時因為提供了operator()(),自己也是function object,而且這些operator()()能夠用執行參數f表示的函數,並傳遞自己擁有的參數給f。