以下代码有什么问题:
#include <ctime> #include <vector> #include <utility> #include <algorithm> #include <iostream> int main() { std::vector< std::pair< char,unsigned > > vec; for( unsigned i = 0; i < 100; ++i ) { char ch = 0; unsigned number = 0; do { ch = i; number = i; } while( std::find( vec.begin(),vec.end(),std::make_pair< char,unsigned >( ch,number ) ) != vec.end() ); std::cout << ch << number << '\n'; vec.push_back( std::make_pair< char,number ) ); } }
它可以很好地编译:
g++ test.cxx
但失败了:
$g++ -std=c++11 test.cxx /tmp test.cxx: In function 'int main()': test.cxx:21:98: error: no matching function for call to 'make_pair(char&,unsigned int&)' test.cxx:21:98: note: candidate is: In file included from /usr/include/c++/4.7/bits/stl_algobase.h:65:0,from /usr/include/c++/4.7/vector:61,from test.cxx:3: /usr/include/c++/4.7/bits/stl_pair.h:268: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&&) /usr/include/c++/4.7/bits/stl_pair.h:268:5: note: template argument deduction/substitution Failed: test.cxx:21:98: note: cannot convert 'ch' (type 'char') to type 'char&&' test.cxx:25:69: error: no matching function for call to 'make_pair(char&,unsigned int&)' test.cxx:25:69: note: candidate is: In file included from /usr/include/c++/4.7/bits/stl_algobase.h:65:0,_T2&&) /usr/include/c++/4.7/bits/stl_pair.h:268:5: note: template argument deduction/substitution Failed: test.cxx:25:69: note: cannot convert 'ch' (type 'char') to type 'char&&'
解决方法
而不是以这种方式显式指定make_pair<>()的模板参数:
std::make_pair< char,number )
只是让他们推断:
std::make_pair( ch,number )
说明:
这个指南背后的基本原理可以通过std :: make_pair<>()的定义方式找到,并且模板参数推导的方式适用于通用引用.根据C 11标准第20.3.3 / 8-9段:
template <class T1,class T2>
pair<V1,V2> make_pair(T1&& x,T2&& y);
Returns:
pair<V1,V2>(std::forward<T1>(x),std::forward<T2>(y));
where V1 and V2 are determined as follows: LetUi
bedecay<Ti>::type
for eachTi
. Then eachVi
isX&
ifUi
equalsreference_wrapper<X>
,otherwiseVi
isUi
. [ Example: In place of:
return pair<int,double>(5,3.1415926); // explicit types
a C++ program may contain:
return make_pair(5,3.1415926); // types are deduced
—end example ]
这里,T1和T2意在推断.通过自己明确指定模板参数,您将开始使用make_pair<>()的类型推导机制来生成正确的返回类型,从而强制实例化接受对char和rvalue的rvalue引用的函数对无符号的引用:
... make_pair(char&&,unsigned&&)
但是,您没有在输入中提供rvalues,因为ch和number是左值.这就是编译器所抱怨的.
替代方案:
另请注意,您可以隐式构造一个std :: pair对象,这样就可以保存您从调用make_pair<>()的过程中:
vec.push_back( { ch,number } );