0

I have a geometry class.

class Geometry
{
private:
    float width;
    float height;
    bool isVisible;
public:
    float getWidth();
    void setWidth(float value);
    float getHeight();
    void setHeight(float value);
    bool getIsVisible();
    void setIsVisible(bool value);
};

The application has a server which receives incoming messages like

Geomery*Width 5;

this message tells the application to set the width of geometry object to 5

so i have a another class which does that

class CommandInterface
{   
    void ProcessCommand( std::string command , std::shared_ptr<Geometry> Geom)
    {
        std::vector<std::string> cmd;
        // split the commandReceived and fill the vector
        if (cmd[1] == "Width")
        {
                Geom->setwidth(atof(cmd[2]));   
        }

       // Other if conditions for other values
    }
};

Can i make the CommandInterface automated ?

currently if i add a new data variable to geometry class i need to add another if condtion to ProcessCommand function.

Summit
  • 2,112
  • 2
  • 12
  • 36
  • 1
    You can use a map to remove cascading `if`-`else` code but you cannot automate the map. You are looking for logic that will translate a string to a member function of the class, which cannot be done. I'll wait for someone smarter than I to prove me wrong :) – R Sahu Mar 20 '20 at 05:50
  • @R Sahu yes i have struggled for a while to get that logic but i am unable to do so. – Summit Mar 20 '20 at 05:53
  • 1
    This would be easy if C++ had something for [reflection](https://en.wikipedia.org/wiki/Reflection_(computer_programming)) but it currently has not. So, you could establish your custom reflection by own code. This, together with templates and (urgh) macros may help to reduce code complication. Qt's meta stuff might be an example (although I'm not sure whether it's a good one), and you probably don't wand/need something complicated like this. – Scheff's Cat Mar 20 '20 at 06:17
  • 1
    I just wrote a sketch how a (very simple) reflection could look like: [**Demo on coliru**](http://coliru.stacked-crooked.com/a/34d9ee26e8e3c86f). It's that simple that I don't dare to post it as answer. ;-) However, have a look at [SO: How can I add reflection to a C++ application?](https://stackoverflow.com/q/41453/7478597) or try [google "c++ reflection"](https://www.google.com/search?q=C%2B%2B+reflection) to find more about this. (And, there was a "typo" in my previous comment. I intended to write _may help to reduce code **duplication**_.) ;-) – Scheff's Cat Mar 20 '20 at 07:38

0 Answers0