c++ - 递归模板模式;类型何时确定?

标签 c++ templates

链接到我的其他问题 ( 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/

相关文章:

c++ - 未分配正在释放的指针 - 如何调试?

c++ - 二叉搜索树 C++

c++ - 整数类型的模板特化如何工作?

C++ 模板类和 Matlab Mex

templates - 了解jsf ui的用途 :composition

constexpr 函数中存在 C++ Wconversion 警告,但模板中没有

c++ - 如何在 C++ 中以编程方式导入 tlb 文件?

C++ 按值返回集合

c++ - 何时使用 std::unique_ptr 作为容器?

c++ - 类外的成员模板函数定义无法构建 Visual Studio 2013