返回模板映射值作为引用
Returning template map value as reference
好吧,我必须说,使用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返回一个临时对,该对已经是一个右值,因此不需要显式移动。
相关文章:
- 智能指针作为无序映射键,并通过引用进行比较
- 拥有映射的现代方法,该映射可以指向或引用已在堆栈上分配的不同类型的数据
- 从函数返回对映射的引用
- 为什么我不能返回带有透明函子的法线映射引用?
- 通过指针或引用将映射传递给函数?
- 将从std::映射中获取的std::pair引用传递给接受std::对引用的函数
- 映射/集迭代器不可取消引用 (C++) - 调试断言失败
- 取消引用映射迭代器时返回对临时的引用
- 有没有办法在不使用循环的情况下非具体地引用映射中的每个值?C++
- lambda 和映射,引用参数 - 编译错误
- 将引用对具有shared_ptr作为值的映射转换为对具有shared_ptr const 作为值的映射的引用
- Boost Intervocess:通过迭代通过从结构引用对象的映射进行迭代时
- 使用双迭代器引用映射中的列表
- 在消息映射中创建按钮和引用
- c++存储映射元组的引用,以便在另一个函数中使用
- 由引用集/映射迭代器传递的迭代器不可取消引用
- 本机C++类与 WinRT 组件(引用类)之间的自动映射
- 引用映射中嵌套对中的值
- 没有用于引用映射的可行重载运算符
- 无法取消引用映射常量迭代器的mapped_type