Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to detect if a type is an iterator or const_iterator

I'm wondering, if there is a way to check at compile time whether a type T of some iterator type is a const_iterator, or not. Is there some difference in the types that iterators define (value_type, pointer, ...) between iterators and const iterators?

I would like to achieve something like this:

typedef std::vector<int> T;

is_const_iterator<T::iterator>::value       // is false
is_const_iterator<T::const_iterator>::value // is true
like image 541
Jan Holecek Avatar asked Mar 24 '11 17:03

Jan Holecek


People also ask

What is the difference between iterator and Const_iterator?

"You would use an iterator that is const when you will just be reading/writing from ONE element in a container. You would use const_iterator when you will just be READING from one or more elements in a container.

What data type is an iterator?

An iterator is an object (like a pointer) that points to an element inside the container. We can use iterators to move through the contents of the container. They can be visualised as something similar to a pointer pointing to some location and we can access content at that particular location using them.

What is constant iterator in C++?

A const iterator points to an element of constant type which means the element which is being pointed to by a const_iterator can't be modified. Though we can still update the iterator (i.e., the iterator can be incremented or decremented but the element it points to can not be changed).


2 Answers

C++03 Solution:

As none of the answer seems correct, here is my attempt which is working with GCC:

template<typename T>
struct is_const_pointer { static const bool value = false; };

template<typename T>
struct is_const_pointer<const T*> { static const bool value = true; };

template <typename TIterator>
struct is_const_iterator
{
    typedef typename std::iterator_traits<TIterator>::pointer pointer;
    static const bool value = is_const_pointer<pointer>::value;
};

Example:

int main()
{
    typedef std::vector<int>::iterator it_type;
    typedef std::vector<int>::const_iterator const_it_type;

    std::cout << (is_const_iterator<it_type>::value) << std::endl;
    std::cout << (is_const_iterator<const_it_type>::value) << std::endl;
}

Output:

0
1

Online Demo : http://ideone.com/TFYcW

like image 95
Nawaz Avatar answered Oct 05 '22 17:10

Nawaz


C++11

template<class IT, class T=decltype(*std::declval<IT>())>    
constexpr bool  
is_const_iterator() {   
        return  ! std::is_assignable <
                decltype( *std::declval<IT>() ),
                T   
        >::value;
}
like image 34
Leonid Volnitsky Avatar answered Oct 05 '22 17:10

Leonid Volnitsky