9
我試着做一個類來輕鬆管理資源(ResourceManager)。模板啓用如果是指針
爲此我使用C++ 11的模板。
這是我做的:
template<class K,class T>
class ResourceManager
{
public:
ResourceManager();
~ResourceManager();
/* code */
void clear();
private :
std::unordered_map<K,T> resource;
template <bool b>
void clear();
};
template<class K,class T>
void ResourceManager<K,T>::clear()
{
clear<std::is_pointer<T>::value>();
};
template<class K,class T>
template<bool b>
void ResourceManager<K,T>::clear<b>()
{
for(auto& x:resource)
delete x.second;
resource.clear();
}
template<class K,class T>
template<>
void ResourceManager<K,T>::clear<false>()
{
resource.clear();
}
總之,我嘗試有不同comportement如果T
是一個指針(自動刪除)。
我試過使用std::enable_if
,但我不明白它是如何工作的,並且這是否是正確的方法。
如果有人可以幫助我...
代碼可以在這裏找到:https://github.com/Krozark/ResourceManager
這正是我想要做的。謝謝。 – Krozark
@Krozark:很高興幫助。我添加了一個建議:考慮使用RAII包裝,比如智能指針,所以你根本不必關心'delete'部分; –
+1好的解決方案,Andy。 – WhozCraig