Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does std::pair have two different constructors for both const reference and forwarding reference parameter?

Tags:

From ISO standard (precisely N4860) std::pair synopsis:

constexpr explicit(see below) pair(const T1& x, const T2& y); // first constructor

template<class U1, class U2>
constexpr explicit(see below) pair(U1&& x, U2&& y); // second constructor

I can't seem to find any reason why the first constructor should be defined in conjunction with perfect forwarding constructor. Isn't perfect forwarding constructor sufficient enough to handle both copy, move cases? In which case does first constructor win in overload resolution?

like image 790
Lewis Liman Avatar asked Aug 16 '20 02:08

Lewis Liman


1 Answers

In which case does first constructor win in overload resolution?

It wins when being passed const lvalues with the exact same type with members of the std::pair, i.e. const T1 and const T2. Both the constructors are exact match and non-template one would win. E.g.

const int i = 0;
const int j = 0;
std::pair<int, int> p(i, j);

The constructor taking forwarding references was added since C++11, I think the 1st one is reserved just for consistency.

like image 126
songyuanyao Avatar answered Sep 30 '22 19:09

songyuanyao