Pergunta

It is well known that make_pair deduces types. That is why it exists and it is convenient. Now see this example:

std::pair <int,int> foo;
std::pair <int,int> bar;

foo = std::make_pair (10,20);
bar = std::make_pair (10.5,'A'); //ok: implicit conversion from pair<double,char>

Now I want to understand when exactly the deduction takes place in the line above:

bar = std::make_pair (10.5,'A');

Does it create a pair then while assigning it implicitly casts double to int and char to int?

Foi útil?

Solução

It first creates a std::pair<double, char> thanks to type deduction of the helper function std::make_pair which creates a pair of exactly the same types than you passed to it, no matter to which type you later assign this pair to.

This object gets then assigned to a std::pair<int,int> which works thanks to a templated assignment operator. This operator basically allows assignable types (U1 to T1, U2 to T2) which internally assigns (in your case) a double to an int and a char to an int.

The language doesn't have a feature which "forecasts" the type of variable where the expression will be used, which would be required to make a pair<int,int> immediately without this step in between.

If you want to avoid that step you have to be explicit when constructing the pair, meaning that you shouldn't use the type deducting std::make_pair but rather std::pair's constructor which requires you to put the explicit types. However, I doubt this will increase performance thanks to optimization.

Outras dicas

To elabourate on chris's comment, take a look at this

bar = std::make_pair (10.5,'A');

is the same as

std::pair <double,char> myPair = std::make_pair (10.5,'A'); 
bar = myPair;

This last line now uses the below assignment operator

template< class U1, class U2 >
pair& operator=( const pair<U1,U2>& other );

Assigns other.first to first and other.second to second

Thus pairs of any type are assignable to each other, as long as the underlying types are assignable.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top