返回模板映射值作为引用

Returning template map value as reference

本文关键字:引用 映射 返回      更新时间:2023-10-16

好吧,我必须说,使用C++模板+由模板组成的stl+尝试快速编写C++11代码是一件痛苦的事情。大多数情况下,有很多奇怪的编译器错误。。。我需要帮助,代码:

#include <SFML/Graphics.hpp>
#include <memory>
#include <map>
template <class T>
class cResourceManager
{
public:
T& get(const std::string & key);
bool add(const std::string & key, const std::shared_ptr<T> & ptr);
private:
std::map <std::string, std::shared_ptr<T> > resources;
};
template <class T>
T& cResourceManager<T>::get(const std::string & key)
{
class std::map<std::string, std::shared_ptr<T>>::const_iterator citr =     resources.find(key);
if (citr != resources.end()) return resources[key];
}
template <class T>
bool cResourceManager<T>::add(const std::string & key, const std::shared_ptr<T> & ptr)
{
if (resources.find(key) == resources.end())
{
if(ptr != nullptr) 
{
resources.insert( std::move( std::make_pair(key, ptr) ) );
return true; 
}
}
return false;
}
int main(int argc, char **argv)
{
cResourceManager<sf::Texture> resmgr;
resmgr.add("key", std::make_shared<sf::Texture>() );
resmgr.get("key");
return 0;
}

在resmgr.get("key")行上,我得到一个错误"main.cpp:19:51:error:从类型为"std::map,std::shared_ptr,std::less>,std:,分配器,std:;shared_ptr>>::mapped_type{aka std::hared_ptr}"的表达式对类型为"sf::Texture&"的引用初始化无效我不知道为什么,使用模板和STL来理解错误对我来说非常困难。我不知道怎么了。

第二件事是一个小问题。在线:resources.insert(std::move(std::make_pair(key,ptr))我需要std::move函数来获得更好的性能吗?因为我想在与共容器一起工作时尽可能避免临时对象,但我不认为我什么都懂,所以我不确定。

谢谢!

错误在这一行:

if (citr != resources.end()) return resources[key];

resources[key]会给您一个std::shared_ptr<T>,但您的函数会返回一个T &。你需要这样的东西:

if (citr != resources.end()) return *resources[key];

如果找不到钥匙,你还需要决定该怎么办。目前,在这种情况下,函数不会返回任何内容。

至于您的另一个问题,make_pair返回一个临时对,该对已经是一个右值,因此不需要显式移动。