lundi 30 août 2021

Why does std::initializer_list in ctor not behave as expected?

#include <vector>

int main()
{
    auto v = std::vector{std::vector<int>{}};
    return v.front().empty(); // error
}

See online demo

However, according to Scott Meyers' Effective Modern C++ (emphasis in original):

If, however, one or more constructors declare a parameter of type std::initializer_list, calls using the braced initialization syntax strongly prefer the overloads taking std::initializer_lists. Strongly. If there's any way for compilers to construe a call using a braced initializer to be a constructor taking a std::initializer_list, compilers will employ that interpretation.

So, I think std::vector{std::vector<int>{}}; should produce an object of std::vector<std::vector<int>> rather than std::vector<int>.

Who is wrong? and why?

Aucun commentaire:

Enregistrer un commentaire