c++ - 如果是指针,则启用模板

标签 c++ templates c++11 std

我尝试制作一个类来轻松管理资源(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();
 }

简而言之,如果 T 是一个指针(自动删除),我尝试有不同的表现。

我尝试使用 std::enable_if,但我不明白它是如何工作的,以及这是否是正确的方法。

如果有人能帮助我...


代码可以在这里找到:https://github.com/Krozark/ResourceManager

最佳答案

您可以只使用基于过载和标记分派(dispatch)的解决方案。您的 clear() 成员函数将以这种方式定义:

void clear()
{
    do_clear(std::is_pointer<T>());
}

并且您的类模板将包含 do_clear() 的两个重载,如下所示:

template<class K,class T>
class ResourceManager
{

    // ...

private:

    void do_clear(std::true_type);
    void do_clear(std::false_type);

};

下面是这两个成员函数的定义:

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();
}

但是请注意,您始终可以选择使用智能指针和其他 RAII 资源包装器来避免在原始指针上显式调用 delete

关于c++ - 如果是指针,则启用模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16554192/

相关文章:

c++ - 我创建了一个库,想知道设计是否效率低下

c++ - 将 unicode 代码点转换为 utf-16

c++ - 在模板中捕获异常类

c++ - A类的定义需要B类的定义,如何在不暴露B定义的情况下暴露A的公共(public)函数?

c++ - 为什么 std::string 没有大小写、格式等方法?

c++ - 使用 "no match"和 "cannot bind lvalue"重载 `operator<<` 时出现 `std::wostream` 和 `std::string` 错误

c++ - 在Qt中释放文件锁

c++ - 如何从控件中正确检索 Unicode 文本?

c++ - 如何正确使用 ifstream 从输入文件中读取数据?

c++ - '.' 标记前缺少模板参数