如何在C ++中实现协变参数类型

问题描述

我试图编写一个矩阵类接口,然后为每种矩阵(例如,行主,列主,稀疏版本等)创建特定的实现,问题是该接口使用IMatrix类,但如果我在重写的方法中使用派生类,则它只会编译失败(因为我猜在C ++协变类型中,仅对返回类型有效吗?)。

class IMatrix
{
    int rows,cols,count;
public:
    virtual ~IMatrix() = 0;
    virtual IMatrix& plus(IMatrix& matrix) = 0;
};

class RMMatrix: public IMatrix // row-major matrix implementation
{
    long double* data;
public:
    ~IMatrix() { delete[] data };
    RMMatrix& plus(IMatrix& matrix) override // this works but then i cannot access matrix.data
    {
        // do addition
    }
};

因此,基本上,我希望能够使用以下函数签名进行覆盖:

RMMatrix& plus(RMMatrix& matrix) override // fails because function signature differs from IMatrix

正如我之前所说,我是OOP C ++的新手,我似乎无法找出正确的方法来实施实现类(例如RMMatrix和其他派生类)来定义这些方法,而无需使用纯虚拟方法在界面中,并且没有dynamic_cast = o 我考虑过使用模板,并将派生的实现类作为参数,但感觉很奇怪= s

解决方法

我不确定,因此我只是将其发布在此处,以根据@n.'pronouns'm的反馈确定这是否是有效的答案(供其他人查看)。

template<class Derived>
class Matrix
{
    int rows,cols,count;
public:
    virtual Derived& plus(Derived& matrix) = 0;
};


class RMMatrix: public Matrix<RMMatrix>
{
    long double* data;
public:
    ~RMMatrix() { delete[] data; };
    RMMatrix& plus(RMMatrix& matrix) override 
    { 
        // do something
    }

};

编辑:如评论中所述,由于Matrix不是抽象类,所以我可以删除析构函数并正确编译