C++具有纯虚函数的模板化返回值
C++ templated return value with pure virtual function
我有一个抽象的 Handle
伪代码示例:
template<class T>
class Handle {
public:
virtual ~Handle () {}
virtual T & operator* () const = 0;
virtual T * operator-> () const = 0;
virtual template<class U> operator Handle<U>* () const = 0; // being lazy with dumb pointer
};
template<class T>
class ConcreteHandle : public Handle<T> {
public:
explicit template<class U> ConcreteHandle (U * obj) : obj(obj) {}
virtual ~ConcreteHandle () {}
virtual T & operator* () const {
return *obj;
}
virtual T * operator-> () const {
return obj;
}
virtual template<class U> operator Handle<U>* () {
return new ConcreteHandle<U>(obj);
}
private:
T * obj;
};
根据要求,这就是我正在做的
class GcPool {
public:
virtual void gc () = 0;
virtual Handle<GcObject> * construct (GcClass clazz) = 0;
};
class CompactingPool : public GcPool {
public:
virtual void gc () { ... }
virtual Handle<GcObject> * construct (GcClass clazz) { ... }
private:
Handle<GcList<Handle<GcObject> > > rootSet; // this will grow in the CompactingPool's own pool
Handle<GcList<Handle<GcObject> > > knownHandles; // this will grow in the CompactingPool's own pool.
};
knownHandles需要与Handle兼容,因此它可以位于CompatingPool的rootSet中。rootSet也是如此。我将引导这些特殊手柄,这样就不会发生鸡和蛋的问题。
virtual template<class U> operator Handle<U>* () const =0;
语言规范不允许使用模板虚函数。
在 ideone 处考虑以下代码,然后看到编译错误:
错误:模板可能不是"虚拟的"
现在你能做什么?一种解决方案是这样的:
template<class T>
class Handle {
public:
typedef typename T::super super; //U = super, which is a superclass of T.
virtual ~Handle () {}
virtual T & operator* () const = 0;
virtual T * operator-> () const = 0;
//not a template now, but still virtual
virtual super operator Handle<super> () const = 0;
};
也就是说,在派生类中定义基类的typedef
,并在Handle
中使用它。像这样:
struct Base {//...};
struct Derived : Base { typedef Base super; //...};
Handle<Derived> handle;
或者,您可以将特征定义为:
struct Base {//... };
struct Derived : Base { //... };
template<typename T> struct super_traits;
struct super_traits<Derived>
{
typedef Base super;
};
template<class T>
class Handle {
public:
typedef typename super_traits<T>::super super; //note this now!
virtual ~Handle () {}
virtual T & operator* () const = 0;
virtual T * operator-> () const = 0;
//not a template now, but still virtual
virtual super operator Handle<super> () const = 0;
};
在我看来,super_traits
是一个更好的解决方案,因为您可以在不编辑派生类的情况下定义派生类的特征。此外,您可以根据需要定义任意数量的类型定义;假设您的派生类有多个基,您可能希望定义许多 typedef,或者最好是类型列表。
相关文章:
- 从python中调用C++函数并获取返回值
- 编译器警告:执行到达值返回函数的末尾而不返回值
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 程序不向函数返回值
- 如何在另一个函数中使用返回值作为参数?
- 编写以 C++ 为单位返回值的函数
- 了解在返回值之前和之后使用 EAX 的函数调用
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 如何将不可移动和不可复制的函数返回值获取到数组中
- G++ 编译器是否在未使用返回值的情况下将 constexpr 函数视为常规函数?
- 为什么当你将函数的返回值乘以零时它不会短路?
- 函数的返回值类型是别名 ***或 *** 布尔值
- 如何在没有返回值的情况下使用(特征)unaryExpr 和 lambda 函数?
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 为什么这个"ctypes"包装函数的返回值是"c_long(0)"而不是&quo
- 函数不显示返回值 - C++
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 将 void 函数更改为返回值函数
- 返回值函数中结构成员赋值的额外拷贝