I want a mechanism to determine in compile time whether an iterator is reverse or not.
Iterator traits can only help with the category of an iterat
#include <iterator>
#include <type_traits>
template<typename Iter>
struct is_reverse_iterator : std::false_type { };
template<typename Iter>
struct is_reverse_iterator<std::reverse_iterator<Iter>>
: std::integral_constant<bool, !is_reverse_iterator<Iter>::value>
{ };
You could also specialize the trait for any user-defined iterators that are reverse iterators.
A simple method. It is easy to use and can determine if something is a reverse iterator or not, and can differentiate between const reverse iterators if needed.
#include <iostream>
template<typename Container, typename T>
using IsRegRevIter = std::is_same<T,typename Container::reverse_iterator>;
template<typename Container, typename T>
using IsConstRevIter = std::is_same<T,typename Container::const_reverse_iterator>;
template<typename Container, typename T>
struct IsRevIter
{
const static bool value = IsRegRevIter<Container,T>::value
|| IsConstRevIter<Container,T>::value;
};
int main()
{
using Container = std::list<int>;
Container myList = {1,2,3,4,5,6};
auto RI = myList.rbegin();
auto I = myList.begin();
std::cout << std::endl << std::boolalpha << IsRevIter<Container,decltype(RI)>::value; //true
std::cout << std::endl << std::boolalpha << IsRegRevIter<Container,decltype(RI)>::value; //true
std::cout << std::endl << std::boolalpha << IsConstRevIter<Container,decltype(RI)>::value; //false (it is not const).
std::cout << std::endl << std::boolalpha << IsRevIter<Container,decltype(I)>::value; //false
return 0;
}
output:
false
true
false
false