I have two almost identical classes, in fact every member function is identical, every member is identical, every member function does exactly the same thing. The only difference between those classes is the way I can define variable of their type:
AllocFactorScientific<102,-2> scientific;
AllocFactorLinear<1.2> linear;
Here are headers for them:
template<double&& Factor>
struct AllocFactorLinear;
template<short Mantissa, short Exponent, short Base = 10>
struct AllocFactorScientific
My question is how can I refactor those functions out of those classes that would allow me to have just one set of functions and not two sets of identical functions.
Extract all the common behavior in a third class (I'm omitting the template arguments in my answer for the sake of clarity) :
class CommonImpl
{
public:
void doSomething() {/* ... */ }
};
I then see two choices (which are, from my point of view at least, pretty much equivalent) :
Make AllocFactorLinear
and AllocFactorScientific
inherit privately from this class, and bring the member functions you wish to expose in scope with a using
directives :
class AllocFactorLinear : CommonImpl
{
public:
using CommonImpl::doSomething;
};
Aggregate the implementation class in AllocFactorLinear
and AllocFactorScientific
and forward all the calls to the private implementation :
class AllocFactorLinear
{
public:
void doSomething() { impl_.doSomething(); }
private:
CommonImpl impl_;
};
I would personally go for the first solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With