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?
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.
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.
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.