Nathan29006781
Nathan29006781

Reputation: 335

How does pair get constructed from an initializer list?

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

Answers (1)

Nathaniel Johnson
Nathaniel Johnson

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:

  1. It has a constructor with an initialization list
  2. It fits the requirements of an initialization list (All elements are of same type)

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

Related Questions