C++11make_pair问题

https://stackoverflow.com/questions/32443181/stdmake-pair-with-c-11

在C++11中使用make_pair一定不要显式给出类型参数,不然会报错

#include <utility>
using namespace std;
int main()
{
  int n=0,m=0;
  auto x=make_pair<int,int>(m,n);//wrong
  auto x=make_pair(m,n);//right
 
  return 0;
}

使用C++11编译将会出错:

$ g++ -std=c++11 testpair.cc 
testpair.cc: In function ‘int main()’:
testpair.cc:6:32: error: no matching function for call to ‘make_pair(int&, int&)’
   auto x=make_pair<int,int>(m,n);
                                ^
testpair.cc:6:32: note: candidate is:
In file included from /usr/local/include/c++/4.8.5/utility:70:0,
                 from testpair.cc:1:
/usr/local/include/c++/4.8.5/bits/stl_pair.h:276:5: note: template<class _T1, class _T2> constexpr std::pair<typename std::__decay_and_strip<_Tp>::__type, typename std::__decay_and_strip<_T2>::__type> std::make_pair(_T1&&, _T2&&)
     make_pair(_T1&& __x, _T2&& __y)
     ^

在C++11之前的版本显式给出类型参数是不会有问题的。

其实make_pair作为模板函数,本来就应该尽可能使用自动的参数推断,而不是画蛇添足地显式给出类型参数。

从报错中可以看出,C++11中的make_pair使用的是万能引用,使用<int,int>实例化模板会将类型推导为int&&,也就是右值引用,而传入的m和n是左值,所以报错。auto x=make_pair<int,int>(0,0);就是正确的,或者auto x=make_pair<int&,int&>(m,n);T推导为T& &&,折叠为T&,而传入的m和n是左值,没有问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值