Reputation: 1527
I have some generic function that is returning some variable of type <T>
. I pass some 2 iterators to the function. Then, I try to calculate the size of the vector with the function distance
. Inside the func I define a new type definition which is called v_size
, but the <T>
type of the vector is unknown. How can I calculate the size of the vector by passing only the iterators?
template<class In, class T>
T my_func(In b, In e)
{
typedef typename vector<T>::size_type v_size;
v_size size = distance(b, e);
...
...
}
Upvotes: 2
Views: 693
Reputation: 1040
You can do 3 things:
Deduct the type via the operator*()
of the iterator:
using v_size = vector<std::remove_reference<decltype(*b)>::type>::size_type;
or deduct the type using the return type of the distance function:
using v_size = std::decltype(distance(b, e));
or, even better, remove the v_size altogether and let the compiler deduct the type: auto size = std::distance(b, e);
Upvotes: 1
Reputation: 172934
If you want to get the type pointed by the iterator, you can use std::iterator_traits. e.g.
template<class In>
auto my_func(In b, In e) -> typename std::iterator_traits<In>::value_type
{
using T = typename std::iterator_traits<In>::value_type;
...
}
BTW: I eliminated the 2nd template parameter T
which only appears in the return type declaration and then can't be automatically deduced. Otherwise you have to specify it explicitly when calling the function.
Upvotes: 2