Re: When should one explicitly instantiate std::make_pair?
On May 28, 7:08 am, K. Frank wrote:
As a simple example, consider:
int i = 3;
int j = 4;
auto p1 = std::make_pair (i, j); // no explicit types
auto p2 = std::make_pair<int, int> (i, j); // explicit
In almost all cases of function templates you are discouraged to
specify the template parameters explicitly. In case of the standard
library function templates the only exception that comes to my mind
right now is std::forward where deduction is turned off on purpose by
using a "nondeducible context" for the parameter type.
The point of make_pair is in fact not having to specify the template
arguments but to have them deduced by the compiler. If you want to be
explicit about it, there is no need to use make_pair at all:
auto p2 = std::pair<int,int>(i,j);
or even
std::pair<int,int> p2 (i,j);
Also, your line
auto p2 = std::make_pair<int, int> (i, j);
does not compile anymore since C++11 because make_pair turned into a
perfect forwarding function template. It's now defined to be
template<class T, class U>
pair<X,Y> make_pair(T && x, U && y);
with some nontrivial type transformation T->X and U->Y. If you specify
T and U to be int, the function parameters x and y will be rvalue
references of type int&& which you cannot initialize with lvalues of
type int. This would be a compile-time error.
But now I see some sample code (on www.cplusplus.com)
where make_pair is used with explicit types.
I don't see these examples. At least they are not here
http://www.cplusplus.com/reference/utility/make_pair/
So what's
the right way to use make_pair, and what's the right
way to think about what's going on?
I think I answered that already. :-)
Thanks.
K. Frank
Cheers!
SG