我几乎没有使用过 C++ 移动功能,所以我不确定我所做的是否正确。如果有人查看我的代码并指出我所犯的任何错误,我将不胜感激。
这个想法是创建一个按键存储的资源映射。资源可能是不可复制和不可移动的。
另外,我的类是否需要构造函数和析构函数定义?
谢谢。
#define TYPE(x) std::identity<decltype(x)>::type
namespace General
{
template<class T>
std::string ToString(const T& x)
{
std::ostringstream ss;
ss << x;
return ss.str();
}
}
namespace General
{
template<class T, class KEY = std::string>
class ResourceManager
{
public:
typedef T ResourceType;
typedef KEY KeyType;
void Load(const KeyType& key, std::unique_ptr<ResourceType>&& resource);
const ResourceType& Read(const KeyType& key) const;
ResourceType& Modify(const KeyType& key);
void Unload(const KeyType& key);
std::unique_ptr<ResourceType>&& Release(const KeyType& key);
void UnloadAll();
private:
std::map<KeyType, std::unique_ptr<ResourceType>> data;
};
}
template<class T, class KEY>
void General::ResourceManager<T, KEY>::Load(const KeyType& key, std::unique_ptr<ResourceType>&& resource)
{
auto find_it = data.lower_bound(key);
if (find_it != data.end() && ! (data.key_comp()(key, find_it->first)))
{
throw std::runtime_error(General::ToString(key) + " already exists!");
}
else
{
data.insert(find_it, TYPE(data)::value_type(key, std::move(resource)));
}
}
template<class T, class KEY>
const typename General::ResourceManager<T, KEY>::ResourceType& General::ResourceManager<T, KEY>::Read(const KeyType& key) const
{
auto find_it = data.find(key);
if (find_it == data.end())
{
throw std::runtime_error(General::ToString(key) + " could not be found!");
}
else
{
return *find_it->second;
}
}
template<class T, class KEY>
typename General::ResourceManager<T, KEY>::ResourceType& General::ResourceManager<T, KEY>::Modify(const KeyType& key)
{
auto find_it = data.find(key);
if (find_it == data.end())
{
throw std::runtime_error(General::ToString(key) + " could not be found!");
}
else
{
return *find_it->second;
}
}
template<class T, class KEY>
void General::ResourceManager<T, KEY>::Unload(const KeyType& key)
{
auto find_it = data.find(key);
if (find_it == data.end())
{
throw std::runtime_error(General::ToString(key) + " could not be found!");
}
else
{
data.erase(find_it);
}
}
template<class T, class KEY>
std::unique_ptr<typename General::ResourceManager<T, KEY>::ResourceType>&& General::ResourceManager<T, KEY>::Release(const KeyType& key)
{
auto find_it = data.find(key);
if (find_it == data.end())
{
throw std::runtime_error(General::ToString(key) + " could not be found!");
}
else
{
auto resource = std::move(find_it->second);
data.erase(find_it);
return std::move(resource);
}
}
template<class T, class KEY>
void General::ResourceManager<T, KEY>::UnloadAll()
{
data.clear();
}