Why are std :: begin () and std :: end () overloaded for std :: initializer_list in C ++ 11?

In C ++ 11 (quoting N3337), std::begin() and std::end() specified as (ยง24.7 [iterator.range] / p2-3)

 template <class C> auto begin(C& c) -> decltype(c.begin()); template <class C> auto begin(const C& c) -> decltype(c.begin()); 

2 Returns: c.begin() .

 template <class C> auto end(C& c) -> decltype(c.end()); template <class C> auto end(const C& c) -> decltype(c.end()); 

3 Refunds: c.end() .

std::initializer_list , however, provides its own overloads for these functions (ยง18.9.3 [support.initlist.range]):

 template<class E> const E* begin(initializer_list<E> il) noexcept; 

1 Returns: il.begin() .

 template<class E> const E* end(initializer_list<E> il) noexcept; 

2 Refunds: il.end() .

It seems that these overloads do nothing behind the base template except (1), which has the noexcept specification, and (2) take their parameter by value. However, copying initializer_list does nothing special (it just copies a couple of pointers or something equally light), therefore (2) does not create differences in behavior. Moreover, the begin() and end() member functions of many standard containers are also noexcept , but std::begin() / std::end() not specified for these containers, so it seems unlikely that the committee specified these overloads only for (1). Why are these overloads provided?

+7
c ++ c ++ 11 initializer-list
source share
1 answer

This is explained in N2930 , which proposes a change to add the overloads in question. My accent:

Summary of proposed changes

  • Define a range for operators without using concepts, using an argument-dependent search for the beginning and end (which always includes the begin and end functions in the std ) to provide an iterator at the beginning and end of the sequence.
  • Specify a range for statements so that lists of arrays and initializers do not have dependencies on <iterator> .
  • Refactor <initializer_list> so that it does not depend on other headers and does not contain other headers.
  • Specify the library headers that are in #include <initializer_list> .

They did not seem to explain why they wanted the <initializer_list> not to have a dependency on <iterator> , but I think a reasonable guess is that the former should be available in a standalone implementation, while the latter might not be (Table 16, ยง 17.6.1.3)

+6
source share

All Articles