考慮下面的代碼:g++ -std=c++11 <filename>.cpp
:如何插入一個const的std :: shared_ptr的到一個std ::地圖
#include <string>
#include <map>
#include <memory>
#include <utility>
#include <iostream>
typedef std::shared_ptr<const std::string> ConstDataTypePtr;
typedef std::map<std::string, ConstDataTypePtr> StrDataTypeMap;
int main()
{
StrDataTypeMap m_nameToType;
ConstDataTypePtr vp_int8(new std::string("RGH"));
m_nameToType.insert(std::make_pair<std::string, ConstDataTypePtr>("int8_t", vp_int8));
return 0;
}
你必須編譯它。
它提供了以下錯誤:
testO.cpp: In function ‘int main()’:
testO.cpp:14:88: error: no matching function for call to ‘make_pair(const char [7], ConstDataTypePtr&)’
m_nameToType.insert(std::make_pair<std::string, ConstDataTypePtr>("int8_t", vp_int8));
^
testO.cpp:14:88: note: candidate is:
In file included from /usr/include/c++/4.8.2/bits/stl_algobase.h:64:0,
from /usr/include/c++/4.8.2/bits/char_traits.h:39,
from /usr/include/c++/4.8.2/string:40,
from testO.cpp:1:
/usr/include/c++/4.8.2/bits/stl_pair.h:276: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&&)
make_pair(_T1&& __x, _T2&& __y)
^
/usr/include/c++/4.8.2/bits/stl_pair.h:276:5: note: template argument deduction/substitution failed:
testO.cpp:14:88: note: cannot convert ‘vp_int8’ (type ‘ConstDataTypePtr {aka std::shared_ptr<const std::basic_string<char> >}’) to type ‘std::shared_ptr<const std::basic_string<char> >&&’
m_nameToType.insert(std::make_pair<std::string, ConstDataTypePtr>("int8_t", vp_int8));
從我正在讀錯誤,編譯期待當我試圖插入到地圖的r值。爲什麼?我在這裏犯了什麼錯誤?
請注意,我從一些現有的代碼中創建了這個代碼片段,它是大型代碼庫的一部分。也許值得一提的是,這段代碼是從Windows上運行的代碼庫中取得的,我有將它移植到Linux的任務。原作者曾使用過std :: tr1 :: shared_ptr。我修改它使用std :: shared_ptr。由於這種變化,我沒有預料到會有什麼影響。
'std :: make_pair'的要點是讓編譯器推導出類型。如果你想提供類型,使用'std :: pair'。 –
Jarod42
將來,請發佈[MCVE],它們實際上會重現您遇到的確切問題。在人們爲您的問題提供解決方案並將其更改爲新問題之後編輯您的問題就是糟糕的形式。並且@PatrykWertka在編輯之前設法解決了您的問題,但是您繼續編輯問題以產生*不同*問題,PatrykWertka的解決方案*仍然解決。 – Yakk