[英]How to achieve covariant parameter types in C++
I'm trying to write a matrix class interface, and then create specific implementations for each kind of matrix (eg row-major, col-major, sparse version etc), the problem is that the interface defines the math operations using the IMatrix class, but if i use the derived classes instead in the overriden methods it just fails to compile (since i guess in C++ covariant types only work for return types right ?).我正在尝试编写一个矩阵类接口,然后为每种矩阵(例如行主、列主、稀疏版本等)创建特定的实现,问题是该接口使用 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
}
};
So basically I'd like to be able to override using this function signature:所以基本上我希望能够使用这个函数签名覆盖:
RMMatrix& plus(RMMatrix& matrix) override // fails because function signature differs from IMatrix
As i've said before, i'm new to OOP C++ and i can't seem to figure out the right way to enforce implementation classes (eg RMMatrix and other derived classes) to define these methods without using a pure virtual in the interface and without dynamic_cast =o I thought about using templates, and giving the derived implementation class as an argument but that feels weird =s正如我之前所说,我是 OOP C++ 的新手,我似乎无法找出在接口中不使用纯虚拟的情况下强制实现类(例如 RMMatrix 和其他派生类)来定义这些方法的正确方法并且没有 dynamic_cast =o 我想过使用模板,并将派生的实现类作为参数,但这感觉很奇怪 =s
I'm not sure, so i'm just posting it here to make sure if this is a valid answer (for others to review) based on @n.'pronouns'm
's feedback.我不确定,所以我只是将它发布在这里以确保这是否是基于
@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
}
};
Edit: As stated in the comment, since Matrix is not an abstract class i can just remove the destructor and it compiles correctly编辑:如评论中所述,由于 Matrix 不是抽象类,因此我可以删除析构函数并正确编译
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.