kfm*_*e04 7 c++ templates c++11
我有以下界面的排序:
template< class RandomIt >
void my_sort( RandomIt first, RandomIt last )
{
}
Run Code Online (Sandbox Code Playgroud)
我期望RandomIt成为一个迭代器std::vector<T>.begin()/end()或一个普通的指针类型T* first,T* last.我想如果我假设RandomIt是一个向量,我可以从中得到它RandomIt::value_type,但是这样就不适用了T* first,T* last.
我的问题是,如何value_type T在两种情况下从模板参数中提取?
ric*_*ici 16
使用iterator_traits<T>::value_type(cppreference).请注意,标准库为T*and 提供了iterator_traits定义const T*,因此它也适用于普通指针.
由于您使用的是C++ 11,因此您可以decltype在迭代器本身上应用以获得value_type:
typedef decltype(*first) value_type;
Run Code Online (Sandbox Code Playgroud)
iterator_traits如果程序员不专门iterator_traits针对他的迭代器,或者他没有定义满足标准要求的迭代器,那么注意可能不适用于程序员定义的类型.
但是,decltype即便如此,这个技巧也会奏效.