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

后端 未结 5 870
死守一世寂寞
死守一世寂寞 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:12

    In theory std::array should be initialized with aggregate initialization. So actually this:

    std::array a {1, 2, 3};
    

    is a syntactic sugar for this:

    std::array a {{1, 2, 3}};
    

    As You see, in the first one it seems I initialize array with values, but it is really aggregate initialization with braced init-list. This is clear as a day in the second situation. So that's for starters.

    Ok so why does not this work?

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

    Well, simply put - the compiler can't distinguish what type of syntax You are using to initialize the array. {1, 11} can be interpreted both as initializer list and use the first version or it can be interpreted as a pair and go with the second version.

    This code:

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

    removes ambiguity.

    Source: http://en.cppreference.com/w/cpp/language/aggregate_initialization

提交回复
热议问题