Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extract the value_type from template parameters (std::vector and plain pointer)?

I have a sort with the following interface:

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

}

I expect RandomIt to be an iterator from std::vector<T>.begin()/end() or a plain pointer-type T* first,T* last. I think if I assume 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 the value_type T from the template parameter in both cases?

like image 567
kfmfe04 Avatar asked Jan 21 '13 04:01

kfmfe04


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 on plain pointers.

like image 83
rici Avatar answered Oct 18 '22 04:10

rici


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

typedef decltype(*first) value_type;

Note iterator_traits may not work for programmer-defined types if the programmer doesn't specialize iterator_traits for his iterators, or he doesn't define iterator meeting Standard requirements.

However, the decltype trick will work even then.

like image 24
Nawaz Avatar answered Oct 18 '22 05:10

Nawaz