This is an unofficial snapshot of the ISO/IEC JTC1 SC22 WG21 Core Issues List revision 116a. See http://www.open-std.org/jtc1/sc22/wg21/ for the official list.

2024-12-19


864. braced-init-list in the range-based for statement

Section: 8.6.5  [stmt.ranged]     Status: C++11     Submitter: James Widman     Date: 7 April, 2009

[Voted into WP at August, 2010 meeting.]

The intent is that the range-based for statement should be able to be used with a braced-init-list as the range over which to iterate. However, this does not work grammatically: a braced-init-list is not an expression, as required by the syntax in 8.6.5 [stmt.ranged] paragraph 1:

Even if this were resolved, the “equivalent to” code is not correct. It contains the declaration,

This has a similar problem, in that 9.2.9.7 [dcl.spec.auto] paragraph 3 requires that the initializer have one of the forms

which does not allow for a braced-initializer-list. In addition, although not allowed by the grammar, 9.2.9.7 [dcl.spec.auto] paragraph 6 treats the braced-init-list specially, in order for the type deduction to work correctly:

Obtain P from T by replacing the occurrences of auto with either a new invented type template parameter U or, if the initializer is a braced-init-list (9.4.5 [dcl.init.list]), with std::initializer_list<U>.

The problem here is that a parenthesized initializer, as in the code expansion of the range-based for statement, is not a braced-init-list.

Proposed resolution (June, 2010):

  1. Change 8.6 [stmt.iter] paragraph 1 as follows:

  2. Iteration statements specify looping.




    [Note: a for-init-statement ends with a semicolon. —end note]

  3. Change 8.6.5 [stmt.ranged] paragraph 1 as follows:

  4. The For a range-based for statement of the form

    let range-init be equivalent to the expression surrounded by parentheses:

    [Footnote: this ensures that a top-level comma operator cannot be reinterpreted as a delimiter between init-declarators in the declaration of __range. —end footnote] and for a range-based for statement of the form

    let range-init be equivalent to the braced-init-list. In each case, a range-based for statement is equivalent to

      {
        auto && __range = ( expression ) range-init;
        for ( auto __begin = begin-expr,
        ...
    

    Note to editor:

    The formatting in the preceding change for range-init follows that of the existing text for begin-expr and end-expr. However, CWG is concerned that this style makes all of these elements look too much like grammar nonterminals and asks that the editor consider some other formatting convention.