gpt4 book ai didi

c++ - 将std::make_pair与std::string一起使用(非右值引用问题)

转载 作者:行者123 更新时间:2023-12-01 15:12:29 25 4
gpt4 key购买 nike

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失败。

  1. 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com