tags:

views:

156

answers:

2

Is the following code portable?

template<typename In>
struct input_sequence_range : public pair<In,In> {
    input_sequence_range(In first, In last) : pair<In,In>(first, last) { }
};

template<typename Arr>
input_sequence_range<Arr*> iseq(Arr* a,
                                typename iterator_traits<Arr*>::difference_type n)
{
    return input_sequence_range<Arr*>(a, a + n);
}

template<typename Iter>
input_sequence_range<Iter> iseq(Iter first, Iter last)
{
    return input_sequence_range<Iter>(first, last);
}

Specifically I question the portability of overloading on std::iterator_traits<>::difference_type. If it's typedeffed to, say, int* (as bizzare as that may be; I think the standard doesn't forbid this) then calling iseq() for an array of ints would be ambiguous.

What does the standard guarantee about iterator_traits<> typedefs?

A: 

According to Josuttis, you should use the typedefs in order to be more flexible and properly generic. All of his examples that started off with something along the lines of "here's a fast way to do it" led to examples that were based on the STL typedefs.

Harper Shelby
+1  A: 

difference_type must be an integral type so int* is out.

Motti