Reputation: 335
Types like array, vector, and map can be constructed from an initializer list like std::vector<int> v = {1,2,3,4,5};
This is good because the initializer list and the vector both have a single type.
I want to know how std::pair<int, std::string> p = {1,"text"};
works. It's not possible for it to be through the initializer list because that must have a single type.
I have heard of piecewise construct, but I don't see how that fits here either.
Upvotes: 2
Views: 1028
Reputation: 4839
It calls the two argument constructor of pair
which then calls the single argument constructors of each specific type.
The compiler will choose a constructor with an initialization list if:
std::pair does not satisfy either requirement so it finds a constructor with matching argument types.
This is the constructor it calls for pair
from stl_pair.h
(gcc 11.2)
explicit constexpr pair(const _T1& __a, const _T2& __b)
: first(__a), second(__b) { }
Since C++17 You can use the following statement too:
std::pair p = {1,"text"};
One thing I would point out is that you are using copy list initialization because of the equal sign rather than direct initialization. This can have some side effects but probably won't.
Good reading here:Constructors and member initializer lists
Upvotes: 1