2

我该如何填写???

template<class...Itrs> struct itr_category { typedef /* ??? */ type; };

所以这type是最专业的,iterator_traits<Itrs>::iterator_category...它支持所有' 操作,否则如果没有单个此类类别,则Itrs失败(如)?enable_if<false>::type

最特iterator_category化是指以下继承中最下降的类型 ( ):

struct input_iterator_tag { };
struct output_iterator_tag { };
struct forward_iterator_tag :       public         input_iterator_tag, 
                                    public        output_iterator_tag { };
struct bidirectional_iterator_tag : public       forward_iterator_tag { };
struct random_access_iterator_tag : public bidirectional_iterator_tag { };

因此,例如,类似的事情itr_category<InputIterator,OutputIterator,...>会失败。

注意:这是一个不同于定义的层次结构std::iterator_traits(参见 24.3 或http://en.cppreference.com/w/cpp/iterator/iterator_tags):这里forward_iterator_tag派生自input_iterator_tagandoutput_iterator_tag而不仅仅是前者。这对应于例如 SGI 文档中描述的继承(参见http://www.sgi.com/tech/stl/Iterators.html)。如果它是相关的,请随意评论这种差异(顺便说一下,这是 zip 迭代器实现的一部分)。

4

2 回答 2

1

首先,您需要一个fold类型的函数,如下所示:

template< template< typename, typename > class f, typename init, typename... types >
class fold;

template< template< typename, typename > class f, typename init >
struct fold< f, init > {
    typedef init type;
};

template< template< typename, typename > class f, typename init, typename type_arg, typename... type_args >
struct fold< f, init, type_arg, type_args... > {
    typedef typename fold< f, typename f< init, type_arg >::type, type_args... >::type type;
};

然后,定义一个组合函数:

template< typename i1, typename i2 >
struct combine_iterators {
private:
    typedef typename iterator_traits< i1 >::category c1;
    typedef typename iterator_traits< i2 >::category c2;
    typedef decltype( false ? ( c1 * )nullptr : ( c2 * )nullptr ) ptype;
public:
    typedef typename std::decay< decltype( *( ptype )nullptr ) >::type type;
};

template<class...Itrs> struct itr_category {
    typedef typename fold< combine_iterators, random_access_iterator_tag, Itrs... >::type type;
};

而且,基本上,就是这样:

class it1;
template<> struct iterator_traits< it1 > {
    typedef bidirectional_iterator_tag category;
};

class it2;
template<> struct iterator_traits< it2 > {
    typedef input_iterator_tag category;
};

class it3;
template<> struct iterator_traits< it3 > {
    typedef output_iterator_tag category;
};

itr_category< it1, it2 >::type x; // typeid( x ).name() == "struct input_iterator_tag"
itr_category< it1, it3 >::type y; // typeid( x ).name() == "struct output_iterator_tag"
itr_category< it2, it3 >::type z; // operand types are incompatible ("input_iterator_tag *" and "output_iterator_tag *")
itr_category< it1, it2, it3 >::type w; // operand types are incompatible ("input_iterator_tag *" and "output_iterator_tag *")
于 2012-08-02T07:32:00.223 回答
1

只需定义一个common_category产生最小值的特征。然后将类型定义为 的类型common_category<firstiter, common_category<seconditer, etc>>。我忘记了这些东西的可变参数模板指令。

于 2012-08-02T06:52:53.490 回答