mercredi 15 juin 2016

Notify create pointer class A to specific instance of class B1 or B2 or B3

Given:

class Propulsion () {}; //abstract
class GenericDualMotor : public Propulsion {}; // also abstract
class Motor1 : public GenericDualMotor () {}; // Concrete
class Motor2 : public GenericDualMotor () {}; // Concrete
class Motor3 : public GenericDualMotor () {}; // Concrete

class Dispatcher { // concrete but not a descendant of Propulsion
public:
    template<class T>
    T *_motor;
    Dispatcher(T motor) : _motor(motor){};

    void forward() {
       _motor->forward();
    }
}; 

the "forward" method is declared in Propulsion as:

virtual void forward(int speed) = 0; // abstract

But in each Motor class, it is declared as concrete:

void forward(int speed) {
     // motor-specific code here...
}

in Main, I declare:

Motor1 motor();
Dispatcher dispatcher(&motor);

This fails to compile with the notice: "error: data member '_motor' cannot be a member template"

What I want to do is decide at compile time which motor type is being used and be able to add new motor types without changing the Dispatcher or GenericDualMotor class code. I suspect that template is the correct mechanism to use here, but I still don't fully "grok" templates. And I imagine this is a simple code fix. Thanks in advance for your help.

Aucun commentaire:

Enregistrer un commentaire