Why does initialization of array of pairs still need double braces in C++14?

后端 未结 5 868
死守一世寂寞
死守一世寂寞 2021-01-31 13:44

With the C++14 standard, the initialization of an std::array can go with single braces (see http://en.cppreference.com/w/cpp/container/array):

This, however

5条回答
  •  星月不相逢
    2021-01-31 14:19

    This appears to be a parsing ambuguity somewhat similar to the famous most vexing parse. I suspect what's going on is that:

    If you write

    std::array, 3> b {{1, 11}, {2, 22}, {3, 33}};
    

    the compiler has two ways to interpret the syntax:

    1. You perform a full-brace initialization (meaning the outermost brace refers to the aggregate initialization of the std::array, while the first innermost one initializes the internal member representation of std::array which is a real C-Array). This will fail to compile, as std::pair subsequently cannot be initialized by 1 (all braces are used up). clang will give a compiler error indicating exactly that:

      error: no viable conversion from 'int' to 'std::pair'
       std::array, 3> a{{1, 11}, {2, 22}, {3, 33}};
                                                ^
      

      Note also this problem is resolved if there is no internal member aggregate to be initialized, i.e.

      std::pair b[3] = {{1, 11}, {2, 22}, {3, 33}};
      

      will compile just fine as aggregate initialization.

    2. (The way you meant it.) You perform a brace-elided initialization, the innermost braces therefore are for aggregate-initialization of the individual pairs, while the braces for the internal array representations are elided. Note that even if there wasn't this ambiguity, as correctly pointed out in rustyx's answer, the rules of brace elision do not apply as std::pair is no aggregate type so the program would still be ill-formed.

    The compiler will prefer option 1. By providing the extra braces, you perform the full-brace initialization and lift any syntactical ambiguity.

提交回复
热议问题