Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define is_iterator type trait?

  • I'm trying to code a is_iterator<T> type trait. Where when T is an iterator type is_iterator<T>::value == true otherwise is is_iterator<T>::value == false.

  • What I tried so far:


template <class, class Enable = void> 
struct is_iterator : std::false_type {};

template <typename T> 
struct is_iterator<T, typename std::enable_if<std::is_pointer<typename
     std::iterator_traits<T>::pointer>::value>::type> : std::true_type {};

LIVE DEMO


Q: Is there a more proper way to define a is_iterator type trait than the one displayed above?

like image 379
101010 Avatar asked Aug 13 '14 15:08

101010


People also ask

Is iterator type trait?

std::iterator_traits is the type trait class that provides uniform interface to the properties of LegacyIterator types. This makes it possible to implement algorithms only in terms of iterators.

How do I find my iterator type?

Iterator type can be checked by using typeid. typeid is a C++ language operator which returns type identification information at run time.

What is Difference_type C++?

difference_type - a type that can be used to identify distance between iterators. value_type - the type of the values that can be obtained by dereferencing the iterator. This type is void for output iterators. pointer - defines a pointer to the type iterated over ( value_type )

What is input iterator?

Input Iterator is an iterator used to read the values from the container. Dereferencing an input iterator allows us to retrieve the value from the container. It does not alter the value of a container. It is a one-way iterator. It can be incremented, but cannot be decremented.


1 Answers

Your check fails if std::iterator_traits<T>::pointer is a type that is not a pointer, for instance if T = std::ostream_iterator<U>.

I think a better test might be whether std::iterator_traits<T>::iterator_category is either std::input_iterator_tag or a derived type, or std::output_iterator_tag.

template <class, class Enable = void> struct is_iterator : std::false_type {};
template <typename T> 
struct is_iterator
<T, 
 typename std::enable_if<
    std::is_base_of<std::input_iterator_tag, typename std::iterator_traits<T>::iterator_category>::value ||
    std::is_same<std::output_iterator_tag, typename std::iterator_traits<T>::iterator_category>::value 
 >::type> 
 : std::true_type {};
like image 138
Praetorian Avatar answered Oct 05 '22 02:10

Praetorian