function object研究之十 storageN

来源:互联网 发布:面向对象编程 表情包 编辑:程序博客网 时间:2024/05/21 22:42

现在看一下storageN模板,定义在storage.hpp文件中:

先来个普通的:

namespace _bi{// 1template<class A1> struct storage1{    explicit storage1( A1 a1 ): a1_( a1 ) {}    template<class V> void accept(V & v) const    {        BOOST_BIND_VISIT_EACH(v, a1_, 0);    }    A1 a1_;};

BOOST_BIND_VISIT_EACH就是visit_each模板,前面已经介绍过了,一个Visitor模式的C++ template实现。

storage1::accept函数接受visitor function object,然后交给visit_each,visit_each函数内部调用visitor function object去使用a1_。

功能很简单,存储一个对象,并且提供accept方法接收观察者并调用之。


storage1提供了两个偏特化版本支持boost::arg<N>参数和返回boost::arg<N>的函数指针。

template<int I> struct storage1< boost::arg<I> >{    explicit storage1( boost::arg<I> ) {}    template<class V> void accept(V &) const { }    static boost::arg<I> a1_() { return boost::arg<I>(); }};template<int I> struct storage1< boost::arg<I> (*) () >{    explicit storage1( boost::arg<I> (*) () ) {}    template<class V> void accept(V &) const { }    static boost::arg<I> a1_() { return boost::arg<I>(); }};

这两个偏特化模板都提供了accept的空实现,所以不要使用它们。

构造函数也没有保存boost::arg<N>对象,甚至都没有a1_成员变量。

特别提供了a1_()静态成员函数用来直接返回boost::arg<I>()


storage2的模板类是从storage1的模板类继承(都不是偏特化版本)

template<class A1, class A2> struct storage2: public storage1<A1>{    typedef storage1<A1> inherited;    storage2( A1 a1, A2 a2 ): storage1<A1>( a1 ), a2_( a2 ) {}    template<class V> void accept(V & v) const    {        inherited::accept(v);        BOOST_BIND_VISIT_EACH(v, a2_, 0);    }    A2 a2_;};

因此storage2有两个成员变量a1_和a2_.

再看看偏特化版本:

template<class A1, int I> struct storage2< A1, boost::arg<I> >: public storage1<A1>{    typedef storage1<A1> inherited;    storage2( A1 a1, boost::arg<I> ): storage1<A1>( a1 ) {}    template<class V> void accept(V & v) const    {        inherited::accept(v);    }    static boost::arg<I> a2_() { return boost::arg<I>(); }};template<class A1, int I> struct storage2< A1, boost::arg<I> (*) () >: public storage1<A1>{    typedef storage1<A1> inherited;    storage2( A1 a1, boost::arg<I> (*) () ): storage1<A1>( a1 ) {}    template<class V> void accept(V & v) const    {        inherited::accept(v);    }    static boost::arg<I> a2_() { return boost::arg<I>(); }};
又加了一个a2_()成员函数返回boost::arg<I>对象而已。

从此以后,一直不断的设计storageN到stoarge9 .

原理还是很简单的。总结:

storageN的模板提供了接受boost::arg<I>相关的偏特化版本。

N从1-9,提供了a1_()到a9_()的成员函数获取boost::arg<1>到boost::arg<9>的占位符对象。