Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't `std::initializer_list` provide a subscript operator?

Suppose that you are writing a function that accepts an std::initializer_list called list, and that the function requires random access to list's elements. It would be convenient to write list[i] instead of list.begin()[i]. So why doesn't std::initializer_list provide a definition of operator[]?

I can't think of any cases where an operator[] returning const T& would not be well-defined. Efficiency doesn't seem to be the issue here, since std::initializer_list<T>::iterator is aliased to const T*, which is clearly a random-access iterator.

like image 965
void-pointer Avatar asked Jul 22 '13 12:07

void-pointer


1 Answers

According to Bjarne Stroustrup in Section 17.3.4.2 (p. 497) of The C++ Programming Language, 4th Edition:

Unfortunately, initializer_list doesn't provide subscripting.

No further reason is given.

My guess is that it's one of these reasons:

  1. it's an omission, or
  2. because the initializer_list class is implemented with an array and you'd have to do bounds checking to provide safe access, it could more easily be used unsafely if that interface was provided, or
  3. to be consistent with the std algorithms iteration paradigm, or
  4. because initializer_lists are, by their nature, ad-hoc, there's more room for error by addressing them directly

2 and 4 sound kind of weak. as does 3. My money's on 1.

like image 87
Homer6 Avatar answered Oct 04 '22 00:10

Homer6