Non-repeating types used as template parameters

Given the code below, is there a better way to do this without repeating typename std::iterator_traits<T>::iterator_categorytwice?

template<class T, class T2>
struct foo :
    bar<
        foo<T, T2>, typename 
        std::conditional<
            std::is_same<typename 
                std::iterator_traits<T>::iterator_category,  //Repeated
                std::random_access_iterator_tag
            >::value,
            std::bidirectional_iterator_tag, typename 
            std::iterator_traits<T>::iterator_category       //Repeated
        >::type
    >
{}
+3
source share
2 answers

Separate it (as it should be anyway):

// put in detail namespace/file or something in real code
template<class T, class T2>
struct foo_base
{
    typedef foo<T, T2> foo_type;
    typedef typename std::iterator_traits<T>::iterator_category category_type;

    static const bool random_access = std::is_same<category_type,
                                        std::random_access_iterator_tag>::value;
    typedef typename std::conditional<random_access,
                                        std::bidirectional_iterator_tag,
                                        category_type>::type tag_type;

    typedef bar<foo_type, tag_type>::type base_type;
}

template<class T, class T2>
struct foo :
   foo_base<T, T2>::base_type
{};

Even if there was no repeated bit, you should still separate it so that the logic of the base type is separated from the actual inheritance of the base type.

+3
source

You can typedefhim:

typedef std::iterator_traits<T>::iterator_category it_cat;
0
source

Source: https://habr.com/ru/post/1772148/


All Articles