Michael Feldmeier
Michael Feldmeier

Reputation: 241

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.

Upvotes: 0

Views: 72

Answers (1)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

The thing you're looking for is called Visitor Pattern or Double Dispatch. You should be able to easily locate further infor online. However, the gist is basically this: With regular virtual functions or OOP, the invoked code depends on the type of one object. With the Visitor Pattern, you get to pick the code depending on two objects (hence also the name Double Dispatch), which is basically what you need.

Upvotes: 1

Related Questions