How to extract value_type parameter from template parameters (std :: vector and simple pointer)?

I have a view with the following interface:

template< class RandomIt > void my_sort( RandomIt first, RandomIt last ) { } 

I expect RandomIt be an iterator from std::vector<T>.begin()/end() or a simple pointer like T* first,T* last . I think if I assume that RandomIt is a vector, I can get it from RandomIt::value_type , but then this will not work for T* first,T* last .

My question is: how can I extract value_type T from a template parameter in both cases?

+7
source share
2 answers

Use iterator_traits<T>::value_type ( cppreference ). Note that the standard library provides iterator_traits definitions for T* and const T* , so it also works with simple pointers.

+16
source

Since you are using C ++ 11, you can apply decltype to the iterator itself to get value_type :

 typedef decltype(*first) value_type; 

Note iterator_traits may not work for types defined by the programmer if the programmer does not specialize in iterator_traits for his iterators, or he does not determine if the iterator meets the standard requirements.

However, the decltype trick will work even then.

+5
source

All Articles