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?
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.
Iterator type can be checked by using typeid. typeid is a C++ language operator which returns type identification information at run time.
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 )
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.
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 {};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With