tags:

views:

272

answers:

3

In order to get an "easier-to-remember" interface to the index-generating function std::distance(a,b), I came up with the idea of a better distinction of it's arguments (when used against the base of a vector: vec.begin() ) by calling a templated function with the vector and its iterator, like:

std::vector<MyType> vect;
std::vector<MyType>::const_iterator iter;
...
...
size_t id = vectorindex_of(iter, vect);

with the rationale of never confusing the order of the arguments ;-)

The explicit formulation of the above idea would read sth. like

 template <typename T>
 inline 
 size_t vectorindex_of( 
          typename std::vector<T>::const_iterator iter, 
          const std::vector<T>& vect ) {

  return std::distance( vect.begin(), iter ); 
 }

... which works but looks awkward.

I'd love to have the template mechanism implicitly deduce the types like (pseudo-code):

 template <typename T>
 inline 
 size_t vectorindex_of(T::const_iterator iter, const T& vect) {
    return std::distance( vect.begin(), iter ); 
 }

... which doesn't work. But why?

Thanks & regards

rb

+2  A: 
 template <typename T>
 inline 
 std::size_t vectorindex_of(typename T::const_iterator iter, const T& vect) {
    return std::distance( vect.begin(), iter ); 
 }

Should work fine (notice the typename). Template arguments should be deduced in either case.

Johannes Schaub - litb
Thanks for pointing out this simple fix. I'd like to tag both of your answers as "accepted answer", but only one is possible ;-)
rubber boots
No worries **` `** **` `** **` `** ` ` ` ` :)
Johannes Schaub - litb
+5  A: 

The fix is easy: add typename before T::const_iterator iter. This is needed because class templates may be specialized and using typename tells the compiler a type name is expected at T::const_iterator and not a value or something.

You do the same in your less generic function, too.

strager
A: 

You might also be interested in the "easier-to-remember" way to get the index of a vector iterator:

i - vec.begin()

It's identical to pointer arithmetic with random access iterators!

AshleysBrain