Class refactoring

I have two almost identical classes, in fact, each member function is identical, each member is identical, each member function does the same. The only difference between these classes is how I can define a variable of their type:

AllocFactorScientific<102,-2> scientific;
AllocFactorLinear<1.2> linear;  

Here are the headings for them:

template<double&& Factor>
struct AllocFactorLinear;

template<short Mantissa, short Exponent, short Base = 10>
struct AllocFactorScientific

My question is how can I reorganize these functions from those classes that would allow me to have only one set of functions, and not two sets of identical functions.

+5
source share
4 answers

Extract all the general behavior in the third class (I'm just omitting the template arguments in my answer):

class CommonImpl
{
public:
  void doSomething() {/* ... */ }
};

(, , , ):

  • AllocFactorLinear AllocFactorScientific -, using:

    class AllocFactorLinear : CommonImpl
    {
    public:
      using CommonImpl::doSomething;
    };
    
  • AllocFactorLinear AllocFactorScientific :

    class AllocFactorLinear
    {
    public:
      void doSomething() { impl_.doSomething(); }
    private:
      CommonImpl impl_;
    };
    

.

+3

, 2 .

+2

? ?

0

, - :

template <typename Type>
struct AllocFactor {...};

Type, :

template <double&& Factor>
struct LinearConfig
{
    static double value() { return Factor;}
};

template <short Mantissa, short Exponent, short Base = 10>
struct FactorScientificConfig
{
    static double value() 
    {
       return some_expression_to_get_factor;
    }
};

You can create AllocFactorusing AllocFactor<LinearConfig<1.2>>and corresponding to FactorScientificConfig. You can then use the static member function to return the value calculated for both classes, so that it AllocFactor<T>can use T::value()as the value specified in the configuration class.

0
source

All Articles