[英]Suppression State Error C2440 'return': cannot convert from '_Ty2 *' to 'std::pair<T *,unsigned int>'
我有源代碼
#include <iostream>
#include <unordered_map>
using namespace std;
template<typename T>
class Tes
{
unordered_map < string, pair<T*, unsigned int>> m_resources;
public:
pair<T*, unsigned int> Find(const string& l_id)
{
auto itr = m_resources.find(l_id);
return (itr != m_resources.end() ? &itr->second : nullptr);
}
};
int main()
{
Tes<int> t;
pair<int*, unsigned int> tes2 = t.Find("tes");
}
它在我的模板中返回 itr 有錯誤。 任何人都可以幫助為什么會發生這種情況? 我在此代碼中使用 unordered_map。並使用對。
好的,所以您嘗試返回指針std::pair<T*, unsigned int>*
但您的成員 function 聲明期望std::pair
按值std::pair<T*, unsigned int>
返回.
要解決此問題,您可以更改 function 聲明以期望返回std::pair<T*, unsigned int>*
。
template<typename T>
class Tes
{
public:
pair<T*, unsigned int>* Find(const string& l_id)
{
auto itr = m_resources.find(l_id);
return itr != m_resources.end() ? &itr->second : nullptr;
}
private:
unordered_map<string, pair<T*, unsigned int>> m_resources;
};
int main()
{
Tes<int> t{};
pair<int*, unsigned int>* tes2 = t.Find("tes");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.