jeudi 2 janvier 2020

Overwrite a class method with a template method in C++

I'm still figuring out C++, and I have not been able to put this together from searching on google. I'm working with a larger project used by other people and I'm trying to expand the functionality of a class without breaking anyone else's code. In particular there is an untouchable Base class and Derived class that both implement a "crunch numbers" method that works on std::vector.

class Base {
 public:
    void crunch_numbers(std::vector& v) { // do stuff to v; }
};

class Derived : public Base {
 public:
    void crunch_numbers(std::vector& v) override { // do different stuff to v; }
};

I'm working with Eigen::Vector, and I was hoping to get away with something like this:

template <typename vec>
class MyDerived : public Base {
 public:
    void crunch_numbers(vec& v) override { // do different stuff to v; }
};

typedef MyDerived<std::vector> Derived;

That would let me work with different vectors and wouldn't break any existing code that uses the Derived class. But, when compiling my code, I get the error error: ‘void MyDerived<vec>::crunch_numbers(vec) [with vec = Eigen::Matrix<double, 2, 1>]’ marked ‘override’, but does not override. ... Because Base class only operates on std::vector.

I can't touch Base class because there may be other derived classes I don't know about. I'd like to have the flexibility to work with different vector types in the future without just adding overloads to Derived class. Is there a way to do this?

Aucun commentaire:

Enregistrer un commentaire