Why can a seemingly acceptable argument list be used to construct std::vector, but not std::array?

49 Views Asked by At

I ran into this odd asymmetry when attempting to initialize a std::array object without specifying either template parameter. Can someone explain why v3 and a4 works, but a3 fails to compile?

#include <vector>
#include <array>

int main()
{
    auto v1 = std::vector<std::pair<int,int>>{ {1,2}, {3,4} };
    auto v2 = std::vector{ std::pair{1,2}, std::pair{3,4} };
    auto v3 = std::vector{ std::pair{1,2}, {3,4} };
    auto v4 = std::vector{ std::initializer_list{ std::pair{1,2}, {3,4} } };

    auto a1 = std::array<std::pair<int,int>, 2>{ {{1,2}, {3,4}} };
    auto a2 = std::array{ std::pair{1,2}, std::pair{3,4} };
    auto a3 = std::array{ std::pair{1,2}, {3,4} }; // <= fails to compile
    auto a4 = std::array{ std::initializer_list{ std::pair{1,2}, {3,4} } };

    return 0;
}
<source>: In function 'int main()':
<source>:13:49: error: class template argument deduction failed:
   13 |     auto a3 = std::array{ std::pair{1,2}, {3,4} }; // <= fails to compile
      |                                                 ^
<source>:13:49: error: no matching function for call to 'array(std::pair<int, int>, <brace-enclosed initializer list>)'

EDIT: I don't necessarily agree that this question is similar to the ones mentioned, since those questions refer to std::array with the type specified, not a std::array without template parameters. Note: This isn't a strong opinion.

0

There are 0 best solutions below