How to check that the passed Iterator is a random access iterator?

If Iterator is a random access iterator, then

std::iterator_traits<Iterator>::iterator_category

will be std::random_access_iterator_tag. The cleanest way to implement this is probably to create a second function template and have Foo call it:

template <typename Iterator>
void FooImpl(Iterator first, Iterator last, std::random_access_iterator_tag) { 
    // ...
}

template <typename Iterator>
void Foo(Iterator first, Iterator last) {
    typedef typename std::iterator_traits<Iterator>::iterator_category category;
    return FooImpl(first, last, category());
}

This has the advantage that you can overload FooImpl for different categories of iterators if you'd like.

Scott Meyers discusses this technique in one of the Effective C++ books (I don't remember which one).


In addition to the tag dispatch, you can compare the category to std::random_access_iterator_tag directly using std::is_same_v:

using category = typename std::iterator_traits<Iterator>::iterator_category;
if constexpr (std::is_same_v<category, std::random_access_iterator_tag>) {
  vec.resize(last - first);
}

This can sometimes lead to a more clear and concise code, particularly if only a small part of your implementation (like reserving the vector size) depends on the iterator category.