Search code examples
c++type-traitsiterator-traits

What is a difference between iterator_category vs iterator_category() in std::iterator_traits


Why in one case I must write iterator_category without parentheses:

template<typename Iterator>
void my_advance(Iterator &iter, int n)
{
    if constexpr(std::is_same_v<
            typename std::iterator_traits<Iterator>::iterator_category,
            std::random_access_iterator_tag>)
        iter += n;
    else
        for(int i = 0; i<n; ++i, ++iter);
}

and in enother case with parentheses:

template<typename Iterator, typename IterCategory>
void my_advance_helper(Iterator &iter, int n, IterCategory){
    for(int i = 0; i < n; ++i, ++iter);
}

template<typename Iterator>
void my_advance_helper(Iterator &iter, int n, std::random_access_iterator_tag){
    iter += n;
}

template<typename Iterator>
void my_advance(Iterator &iter, int n)
{
    my_advance_helper(iter, n,
    typename std::iterator_traits<Iterator>::iterator_category());
}

If as i understand, iterator_traits::iterator_category is just a typedef. What do parentheses do in last case? Do they return actual value of iterator_category in this way? Seems pretty obvious, but I need some confirmation. Sorry for possibly stupidity of question =)


Solution

  • If as i understand, iterator_traits::iterator_category is just a typedef

    Correct.

    What do parentheses do in last case?

    That's syntax for value initialisation of a temporary object.