Search code examples
c++classoptimizationreusability

How to reuse the same implementation method for diferent classes


I'm practicing c++ and I got stuck on the following codes trying to optimize them. I'd like to know if there is something I can do to optimize their method's implementation. Because the methods are the same except for the consts. Thanks in advance.

dominios.h

class HP {
private:

  int valor;

  static const int LIMITE_INFERIOR = 0;
  static const int LIMITE_SUPERIOR = 1000;

public:

  void setValor(int);
  int getValor() {
    return valor;
  }
};

class MP {
private:

  int valor;

  static const int LIMITE_INFERIOR = 0;
  static const int LIMITE_SUPERIOR = 500;

public:

  void setValor(int);
  int getValor() {
    return valor;
  }
};

dominios.cpp

void HP::setValor(int valor) {

  if (valor < LIMITE_INFERIOR) this->valor = LIMITE_INFERIOR;
  else if (valor > LIMITE_SUPERIOR) this->valor = LIMITE_SUPERIOR;
  else this->valor = valor;
}

void MP::setValor(int valor) {

  if (valor < LIMITE_INFERIOR) this->valor = LIMITE_INFERIOR;
  else if (valor > LIMITE_SUPERIOR) this->valor = LIMITE_SUPERIOR;
  else this->valor = valor;
}

As you can see the setValor of both classes are the same. I tried to do hierarchy using a "template" but that didn't work for me because of the consts.


Solution

  • this->valor = std::clamp(valor, LIMITE_INFERIOR, LIMITE_SUPERIOR);
    

    template <typename Tag, int lo, int hi>
    class Metric {
    private:
      int valor;
    
    public:
      void setValor(int v) { valor = std::clamp(v, lo, hi); }
      int getValor() { return valor; }
    };
    
    struct HPTag;
    using HP = Metric<HPTag, 0, 1000>;
    
    struct MPTag;
    using MP = Metric<MPTag, 0, 500>;