dimanche 27 octobre 2019

WHat is a good pattern/implementation for this inheritence-like situation?

Let's say I have two different implementations of mathematical vectors (and other mathematical structures such as matrices).

class SparseVector {
  double dotproduct(SparseVector& other);
};

class DenseVector {
  double dotproduct(DenseVector& other);
};

I would like to implement algorithm that are using either exclusively sparse or dense algebra. Of course I would like to only implement a generic version of the algorithm what can deal with either of the two.

The first idea was to create a virtual vector class (code below for the concept, it wouldn't actually work this way):

class Vector {
  virtual double dotproduct(Vector& other);
};

class SparseVector : public Vector {
  double dotproduct(SparseVector& other) override;
};

class DenseVector : public Vector  {
  double dotproduct(DenseVector& other) override;
};

However that doesn't work because each of the Vector implementations can only work with other vectors of the same type. (That is, the implementation should not allow a dotproduct between a sparse and a dense vector).

Is there a good implementation strategy or design pattern that prevents me having to implement algorithms twice?

The question is not the same as this one, as I do not want to support dotproducts between a sparse and a dense vector.

I was thinking about using templates:

template<class T>
    class algorithm {
}

but I don't know how to restrict T to be one of SparseVector/DenseVector, so the compiler knows that there exists a suitable dotproduct() function.

Aucun commentaire:

Enregistrer un commentaire