Consider the following C++ Program
#include<map>
#include<iostream>
int main() {
int a = 5, b = 7;
auto pair = std::make_pair<int, int>(a,b);
return 0;
}
Using VC11 and also in gcc-4.7.2 fails with different errors, though it seems to be related and VC11 error message is more meaningful
You cannot bind an lvalue to an rvalue
What I understand from this failure is
make_pair(_Ty1&& _Val1, const _Ty2& _Val2)
which can accept only an rvalue reference. Prior VC++ version example VC10 had two versions, one to accept an lvalue and another an rvalue referenceint & a = b * 5
is invalid.std::move
to convert the lvalue
to rvalue
reference and the call would be successful.std::make_pair
accepts two different types for each of the parameters, Template Argument Resolution in all possible cases can resolve the type of the parameter and an explicitly specifying the type is not required.This scenario seems trivial and the incompatibility can easily be resolved by removing the explicit type specification and making the definition as
auto pair = std::make_pair(a,b);
std::make_pair
exists for the sole purpose of exploiting type deduction to avoid typing the names of the types. That's why there is only one overload (and it should take two universal references, not one universal reference and an lvalue reference to const as VC seems to think).
template <class T1, class T2>
constexpr pair<V1, V2> make_pair(T1&& x, T2&& y);
If you want to type the types explicitly, you can just use the pair constructor. It is even shorter...
auto pair = std::pair<int, int>(a,b);
When you do std::make_pair<int, int>
, you are forcing the template arguments T1
and T2
to both be deduced as int
. This gives you the function as std::pair<int,int> make_pair(int&&, int&&)
. Now these arguments can only take rvalues because they are rvalue references.
However, when the types of T1
and T2
are being deduced by template type deduction, they act as "universal references". That is, if they receive an lvalue argument they will be lvalue references and if they receive an rvalue argument they will be rvalue references. This gives make_pair
the ability to do perfect forwarding.
So the point is, don't explicitly give the template type arguments. The whole point of make_pair
is that it deduces the types itself. If you name the types, it can't do perfect forwarding any more and will fail for lvalue arguments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With