vendredi 10 juin 2016

C++ Design: Overloading/Overriding many many functions, way to clean up?


The case I am trying to implement here is a Base class which has a function (let's call it modify_command) which can accept many different types virtually so derived classes can implement the modify_command function as they see fit. Right now I have something along these lines in the base class:

class Base 
{
    template<typename Command>
    void modify_command(Command cmd)
    { 
        std::cout << "Modify command called with unimplemented command type:" << typeid(cmd).name();
    }

    virtual void modify_command(SpecificCommandA cmd)
    {
         modify_command<SpecificCommandA>(cmd); // Calls the templated function
    }

    virtual void modify_command(SpecificCommandB cmd)
    {
         modify_command<SpecificCommandB>(cmd); // Calls the templated function
    }

    // etc.
};

Then in a derived class:

class Derived : public Base
{
    virtual void modify_command(SpecificCommandA cmd)
    {
        cmd.x = 1;
        cmd.y = 2;
    }
}

Obviously virtual template function isn't a possibility so in some form I am going to have to list function declarations for umpteen many argument possibilities which is sure to clutter the class definition and may make it difficult (over time) for additional command types to be handled

The purpose of having the templated function is for this case to compile without needing definition of modify_command(SpecificCommandC) to log an error:

Base * base = new Derived();
SpecificCommandA a;
SpecificCommandB b;
SpecificCommandC c;
base->modify_command(a); //Set's x and y
base->modify_command(b); //Outputs that command type is unimplemented
base->modify_command(c); //Outputs that command type is unimplemented

I really hate how I have this working, does anyone have a suggestion on how this can be cleaned up / reimplemented? The number of commands while continue to grow as the software matures, so extensibility is a must.


Aucun commentaire:

Enregistrer un commentaire