std::pair<Url, std::string> UrlParser::parse()
{
return std::make_pair({ extract_scheme(), extract_hostname(), extract_port(),
extract_path(), extract_filename() }, host_ip_);
}
host_ip_
变量定义为std::string host_ip_;
我懂了UrlParser.cpp:91:64: error: no matching function for call to 'make_pair(<brace-enclosed initializer list>, std::string&)'
91 | extract_path(), extract_filename() }, host_ip_);
问题出在host_ip_
变量上。如果是std::string
,那么返回它有什么问题?我找到了c++11 rvalue references in `std::make_pair`,这说明我们无法使用非右值引用调用
std::make_pair
,因此我尝试了std::make_pair({ extract_scheme(), extract_hostname(), extract_port(),
extract_path(), extract_filename() }, std::move(host_ip_));
但我明白了error: no matching function for call to 'make_pair(<brace-enclosed initializer list>, std::remove_reference<std::__cxx11::basic_string<char>&>::type)'
91 | extract_path(), extract_filename() }, std::move(host_ip_));
顺便说一句,为什么在提供的链接中,int
是右值引用而const int
不是?
最佳答案
这个问题与将host_ip_
作为左值或右值传递给 std::make_pair
无关;两者都应该工作正常。相反,由于template argument deduction,大括号初始化列表{ extract_scheme(), extract_hostname(), extract_port(), extract_path(), extract_filename() }
使得std::make_pair
的第一个模板参数non-deduced context失败。
- The parameter P, whose A is a braced-init-list, but P is not
std::initializer_list
, a reference to one (possibly cv-qualified), or a reference to an array:
您可以显式传递
Url
,return std::make_pair(Url{ extract_scheme(), extract_hostname(), extract_port(),
// ^^^
extract_path(), extract_filename() }, host_ip_);
或显式指定模板参数。return std::make_pair<Url>({ extract_scheme(), extract_hostname(), extract_port(),
// ^^^^^
// specify the 1st template argument, left the 2nd one to be deduced
extract_path(), extract_filename() }, host_ip_);
关于c++ - 将std::make_pair与std::string一起使用(非右值引用问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63156964/