如何在默认模板参数中引用 self 类型
How to reference self type in default template arguments?
我们有一个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);
}
};
魔杖盒上的现场示例
template <class T, class D_in = void>
class reference_counted: T
{
public:
using D = std::conditional_t<
std::is_same_v<D_in, void>,
default_deallocator<reference_counted>,
D_in
>;
void retain() {ref_count++;}
void release() {
ref_count --;
if (ref_count == 0) {
D deallocator;
deallocator.operator()(this);
}
}
};
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何在默认模板参数中引用 self 类型
- 如何从被传递的对象中通过引用传递 self
- 类实例持有对自身的引用 - self
- 为什么有些类方法返回"*this"(self的对象引用)?
- 为什么通过引用传递self会导致错误的访问
- 无法让 Lua 函数引用"self"
- 如何在声明当前命名空间时引用它?有没有像"self"/"this"这样的词?