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
"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.
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.
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).
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
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;
}
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