mercredi 7 août 2019

Stuck on Design due to the functionality varying at run time

I have a class in my C++/Qt application which has some member variables whose data type can differ at run time depending on which option user has selected. Those member variables have corresponding getter and setter methods.

Now, I tried to solve this problem using the following 2 approaches but none of them worked.

Approach 1: I made a base class "Property" and derived 3 classes from it, namely "IntProperty", "FloatProperty" and "StringProperty". Now these 3 classes have the corresponding member variables with int, float and string type respectively and their getters and setters. I kept the common member variables and methods in base class. The problem is that I am not able to invoke the methods of Derived classes using Base class object. Please the code corresponding to Approach 1 for more clarity.

Approach 2: I tried to solve it using templates but the problem with it is that the user program is a Qt class which has Q_OBJECT macro defined in it and it errors out saying cannot use templates with Q_OBJECT. See code for approach 2 for clarity.

I am stuck in it and cannot think of a design pattern or other technique using which I can tackle this problem. I have been programming sleeplessly for few nights and will be dead by tomorrow if I don't get the answer.

class Base
{
   ...
}

class IntProperty : public Base 
{
  public:
    int getProp() { return prop; }
  private:
    int prop;
}

class FloatProperty : public Base 
{
  public:
    double getProp() { return prop; }
  private:
    double prop;
}

class StringProperty : public Base 
{
  public:
    string getProp() { return prop; }
  private:
    string prop;
}

class UserProgram : public QDialog
{
    Q_OBJECT

  private:
    Base* base;

  public:
    void user()
    {
        /// Trying to take the advantage of runtime polymorphism
        Base* base = new IntProperty();
        base->getProp(); /// compile time error. Ofcourse because there is no
                         /// method named getrop() in Base class. I am unable 
                         /// to decide what should I keep the return type for 
                         /// it.
    }
}


/******************* Approach 2 *********************/
template <typename T>
class Base
{
  private:
    T prop;
  public:
    T getProp() { return prop; }
}

template <typename T>
class UserProgram() : public QDialog
{
    Q_OBJECT
  public:
    void user() 
    {
        base = new Base<T>;
    }
  private:
    Base<T>* base; /// error cannot use template with Q_OBJECT
}

Aucun commentaire:

Enregistrer un commentaire