mardi 3 novembre 2020

How to achieve covarient parameter types in C++

I'm trying to write a matrix class interface, and then create specific implementations for each kind of matrix (e.g. 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 ?).

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 (e.g. 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

Aucun commentaire:

Enregistrer un commentaire