Reputation: 3407
Below code is class initializer list which is provided in Ubuntu standard package. In this iterator and const_iterator are typedef of same type. I just wanted to know why would we like to have same typedef for different type of Iterator ? Ideally for Iterator it should have typedef _E* iterator.
// In the class initializer list:
namespace std
{
/// initializer_list
template<class _E>
class initializer_list
{
public:
typedef _E value_type;
typedef const _E& reference;
typedef const _E& const_reference;
typedef size_t size_type;
typedef const _E* iterator;
typedef const _E* const_iterator;
P.S: I am not able to think of suitable title so I have given this title
Upvotes: 1
Views: 2193
Reputation: 110658
To meet the requirements for a Container, both types iterator
an const_iterator
must exist. Many algorithms and lots of code rely on containers having both of these types available. There's no reason the iterator
type has to be a non-const
(mutable) iterator, however. In this case, they've decided that both iterator
and const_iterator
are const
(immutable) iterators.
The reason they have both iterators as const
is because they clearly don't want to you to be able to change the values in the initializer_list
.
As another example of this, take a look at std::set
whose iterator
and const_iterator
types are also both constant iterators. Since std::set
s contain ordered elements, if you were to be able to change the contents of the std::set
, that ordering would be invalidated. To prevent this, both iterator types are made immutable.
Upvotes: 5
Reputation: 7766
It's probably because you don't ever want to change the values stored inside of an initializer list. They're meant to be temporary objects to be passed up into constructors.
C++ has an (informal, for now) ideal called Concepts that apply to generic types. The Container concept requires certain typedefs to be available for your object. Since std::initializer_list is a container, it requires both ::iterator and ::const_iterator typedefs. However, like std::set, you don't want to let the user modify the elements inside of the initializer_list, and so the ::iterator is the same as ::const_iterator: they're both read-only.
Upvotes: 0
Reputation: 272517
Because these fields are required by any type that satisfies the requirements of Container
. It just so happens that in the case of
std::initializer_list
, the iterator
and the const_iterator
are the same.
Upvotes: 2