Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if iterator's type is reverse_iterator

Is there a way to check if iterator passed as arg to fnc is reverse_iterator? Are there any iterator traits function I could use?

like image 272
There is nothing we can do Avatar asked Feb 15 '16 11:02

There is nothing we can do


2 Answers

It's trivial to write with a partial specialization:

#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::true_type { };

Although as pointed out below, this doesn't handle the (IMHO unlikely) case of a "reverse-reverse" iterator. The slightly less trivial version in Bathsheba's answer handles that case correctly.

like image 151
Jonathan Wakely Avatar answered Nov 18 '22 10:11

Jonathan Wakely


Some code I use in production:

#include <iterator>
#include <type_traits>
template<typename I>
struct is_reverse_iterator : std::false_type
{
};

template<typename I>
struct is_reverse_iterator<std::reverse_iterator<I>>
: std::integral_constant<bool, !is_reverse_iterator<I>::value>
{
};
like image 7
Bathsheba Avatar answered Nov 18 '22 10:11

Bathsheba