问题描述
对不起,标题不好...我有一个类似的基类:
Sorry for the bad title... I have a base class like:
template<class T>
class GPtr
{
public:
typedef T BaseType;
GPtr& operator=(const BaseType& rhs)
{
...
}
};
我经常想做诸如以下的子类专长:
I often want to make subclassed specializations like:
class GraphicPtr : public GPtr<Graphic>
{
...
};
但是,我的基类赋值运算符仍然返回GPtr<Graphic>
而不是GraphicPtr
,并且如果核心赋值运算符功能稍后需要更改,则必须复制粘贴代码很烦人.
However my base-class assignment operator still returns GPtr<Graphic>
not GraphicPtr
and it's annoying to have to copy-paste code in case the core assignment operator functionality should change later.
是否有一种巧妙的方法来定义基类的赋值运算符,以便它返回所使用的实际类的类型?
Is there a neat way to define the base-class assignment operator so it returns the type of the actual class in use?
推荐答案
在C ++中,基类不知道它是子类.您可以添加一个模板参数,它将作为派生类并使用它.
In C++, the base class has no idea of it's children. You may add a template parameter that will be the derived class and use it.
template<class T, class Derived>
class GPtr
{
public:
typedef T BaseType;
Derived& operator=(const BaseType& rhs)
{
...
}
};
这篇关于我可以在返回子类类型的基类上做赋值运算符吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!