function object研究之listN分析
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。
补充:软件开发 , C++ ,