c++ - 如何在默认模板参数中引用自身类型?

标签 c++ c++11 templates standards c++-standard-library

我们有一个 reference_counted 模板和一个默认的 default_deallocator 类如下:

template <class T>
class default_deallocator {
     void operator()(T* obj) {
         delete obj;
     }
};

template <class T>
class reference_counted: T
{
public:
   void retain() {ref_count++;}
   void release() {
        ref_count --;
        if (ref_count == 0) {
            delete this;
        }
   }
}

我们想为 reference_counted 类添加释放器。但是我们不知道如何编写默认模板参数,因为编译器会提示递归类型引用。

//VS2015 says: fatal error C1202: recursive type or function dependency context too complex
template <class T, class D = default_deallocator<reference_counted<T>>>  <---
class reference_counted: T
{
public:
   void retain() {ref_count++;}
   void release() {
        ref_count --;
        if (ref_count == 0) {
            D deallocator;
            deallocator.operator()(this);
        }
   }
}

我理解这个错误。 那么问题是如何在模板默认参数或其他方式中引用当前类类型来实现这种设计模式?

最佳答案

您可以使用更高级的类型(“模板模板参数”):

template <class T, template <typename...> class D = default_deallocator>  
class reference_counted: T
{
public:
   void retain() {}
   void release() {

        D<reference_counted<T, D>> deallocator;
        deallocator(this);

   }
};

live example on wandbox

关于c++ - 如何在默认模板参数中引用自身类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43045610/

相关文章:

c++ - 你能捕获递归 lambda 中的引用吗?

c++ - 为什么内联用户提供的构造函数 odr 使用基类构造函数?

c++ - 为什么 mem_fn() 提示尝试使用已删除的函数?

c++ - 模板参数的条件数值约束

c++ - OpenCV C++ 中的矩阵复共轭

C++ 为什么这段代码可以编译?

c++ - 为什么 std::vector::data 和 std::string::data 不同?

使用模板的 C++ 方法定义

c++ - 使用 mpl::if_ 和整数模板参数选择类型

c++ - 使用 string 和 int(like) 类型初始化模板类的静态成员