错误:调用"make_pair"没有匹配函数

error: no matching function for call to 'make_pair'

本文关键字:quot 函数 make 调用 错误 pair      更新时间:2023-10-16

我想将两个局部变量放入一对并返回它,这是我的代码:

#include <utility>
class Foo {
};
class Bar {
};
std::pair<Foo, Bar> test() {
Foo foo;
Bar bar;
return std::make_pair<Foo, Bar>(foo, bar);
}

我得到了

main.cpp:92:10: error: no matching function for call to 'make_pair'   
/usr/bin/../lib/gcc/x86_64-linux-gnu/7.4.0/../../../../include/c++/7.4.0/bits/stl_pair.h:524:5:
note: candidate function not viable: no known conversion from 'Foo' to 'Foo &&' for 1st argument
make_pair(_T1&& __x, _T2&& __y)

,如果我使用return std::make_pair<Foo, Bar>(std::move(foo), std::move(bar));,编译将成功。那么我错过了什么?

template< class T1, class T2 >
std::pair<V1,V2> make_pair( T1&& t, T2&& u );

由于您在模板参数列表中显式放置了类型<Foo,Bar>,因此禁用了类型推断,并且make_pair具有签名make_pair(Foo&&, Bar&&).您正在传递左值,因此不能绑定到右值引用。不要将类型放在<>或使用pair<Foo,Bar>(foo,bar)

另一种解决方案是依靠类型推导:make_pair(foo,bar)签名make_pair(Foo&, Bar&),一切正常。