Jon
Jon

Reputation: 33

Not repeating types used as template parameters

Given the code below is there a nicer way to right it that doesn't repeat typename std::iterator_traits<T>::iterator_category twice?

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
    >
{}

Upvotes: 3

Views: 206

Answers (2)

GManNickG
GManNickG

Reputation: 503855

Split it up (like 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 split it up to keep the base type logic separate from actually inheriting the base type.

Upvotes: 3

Flinsch
Flinsch

Reputation: 4341

You could typedef it:

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

Upvotes: 0

Related Questions