链接到我的其他问题 ( Can I make an assignment operator on a base class that returns sub-class type ) 我有这个构造,我的想法是我想从 GPtrBase
派生专门的类型无需每次都重写赋值运算符:
template<class BaseType,class Self>
class GPtrBase
{
public:
...
Self& operator=(const BaseType& rhs)
{
...
return *this;
}
};
然而,当我专注于:
class GDrawablePtr : public GPtrBase<MyDrawable,GDrawablePtr>
我收到错误:
'return' : cannot convert from 'GPtrBase<Base,Self>' to 'GDrawablePtr &'
我认为模板类是根据使用的特化生成的,所以不应该*this
类型为 GDrawablePtr
首先?
更新:如果我添加 using GPtrBase::operator=;
,我会注意到它然后工作,即使GDrawablePtr
绝对不定义任何运算符。
最佳答案
与 virtual
函数中的 this
指针自动从 base 向下转换为 derived 的动态多态性相反,您需要使用显式的 static_cast
到派生类
template<class BaseType,class Self>
class GPtrBase
{
public:
...
Self& operator=(const BaseType& rhs)
{
...
return static_cast<Self&>(*this);
}
};
关于c++ - 递归模板模式;类型何时确定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16212828/