I have the following code, which does some iterator arithmetic:
template<class Iterator>
void Foo(Iterator first, Iterator last) {
typedef typename Iterator::value_type Value;
std::vector<Value> vec;
vec.resize(last - first);
// ...
}
The (last - first) expression works (AFAIK) only for random access iterators (like the ones from vector and deque). How can I check in the code that the passed iterator meets this requirement?
If
Iteratoris a random access iterator, thenwill be
std::random_access_iterator_tag. The cleanest way to implement this is probably to create a second function template and haveFoocall it:This has the advantage that you can overload
FooImplfor 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).