繁体   English   中英

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

[英]How to achieve covariant parameter types in 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 不是抽象类,因此我可以删除析构函数并正确编译

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM