简体   繁体   中英

Suppression State Error C2440 'return': cannot convert from '_Ty2 *' to 'std::pair<T *,unsigned int>'

i have a source code

#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");
}

it has error in return itr in my template. can anybody help why this happen?? i use the unordered_map in this code.and using pair.

OK, so you're attempting to return a pointer std::pair<T*, unsigned int>* but your member function declaration expects a std::pair to be returned by value std::pair<T*, unsigned int> .

To fix the issue you can change the function declaration to expect a std::pair<T*, unsigned int>* to be returned.

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM