Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template enable if is pointer

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

like image 340
Krozark Avatar asked May 14 '13 23:05

Krozark


1 Answers

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.

like image 71
Andy Prowl Avatar answered Sep 30 '22 14:09

Andy Prowl