簡體   English   中英

將 std::make_pair 與 std::string 一起使用(非右值引用問題)

[英]Using std::make_pair with std::string (non rvalue reference problem)

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 ,那么返回它有什么問題?

在 `std::make_pair` 中找到了 c++11 右值引用,這解釋了我們不能用非右值引用調用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無關; 兩者都應該可以正常工作。 相反,braced-init-list { extract_scheme(), extract_hostname(), extract_port(), extract_path(), extract_filename() }使std::make_pair的第一個模板參數的模板參數推導失敗,因為非推導上下文.

  1. 參數 P,其 A 是一個花括號初始化列表,但 P 不是std::initializer_list 、對一個的引用(可能是 cv 限定的)或對數組的引用:

您可以明確傳遞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_);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM