Marius
Marius

Reputation: 2273

std::make_pair automatic type deduction?

Consider this function:

std::pair<int, double> getPair()
{
    return std::make_pair(0, 0);
}

Why does this compile?

Shouldn't make_pair return a std::pair<int, int> which is incompatible with std::pair<int, double>? Where is the conversion from int to double taking place?

Link to example code: https://ideone.com/Zq6ooY

Upvotes: 3

Views: 287

Answers (1)

Quimby
Quimby

Reputation: 19113

std::make_pair(0, 0); indeed creates a std::pair<int,int> object. But, you are incorrect about incompatibility of pairs. They are compatible if their arguments are.

See cppreference:

// #4
template< class U1, class U2 >
constexpr std::pair<T1,T2>( const pair<U1, U2>& p );
// #5
template< class U1, class U2 >
constexpr std::pair<T1,T2>( pair<U1, U2>&& p );

These are enabled if the types TX can be constructed from types UX, in your case #5 is used because int can be constructed from double&&.

Upvotes: 4

Related Questions