I try to make a class to manage resources easily (ResourceManager).
For that I use the template with C++11.
Here's what I do:
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();
}
In short, I try to have different comportement if T
is a pointer (auto delete).
I tried to use std::enable_if
, but I did not understand how it functioned, and if this is the right way to take.
If someone could help me...
Code can be found here: https://github.com/Krozark/ResourceManager
You could just use a solution based on overload and tag dispatching. Your clear()
member function would be defined this way:
void clear()
{
do_clear(std::is_pointer<T>());
}
And your class template would include two overloads of do_clear()
, as follows:
template<class K,class T>
class ResourceManager
{
// ...
private:
void do_clear(std::true_type);
void do_clear(std::false_type);
};
And here is the definition of those two member functions:
template<class K, class T>
void ResourceManager<K, T>::do_clear(std::true_type)
{
for(auto& x:resource)
delete x.second;
resource.clear();
}
template<class K, class T>
void ResourceManager<K, T>::do_clear(std::false_type)
{
resource.clear();
}
Notice, however, that you always have the option of using smart pointers and other RAII resource wrappers to avoid calling delete
explicitly on raw pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With