I've been having some difficulties with duplicated code in one of my inheritance hierarchy. How could I avoid duplicating the code inside function smile()?
Given the fact that the variable _a
doesn't exists in the base class I cannot move the function there. Also creating a template function like this template<typename T> void smile(T& a) { a++; }
is not really a solution for me. My actual code is a bit more complicated and such a solution would be very messy if not impossible to apply with my current design.
class com
{
public:
com(int x, float y) : _x(2), _y(1.15f)
{ }
protected:
// Common functions go here .We need this base class.
protected:
int _x;
float _y;
};
class com_int : public com
{
public:
void fill()
{ _a = std::max(_x, (int)_y); }
protected:
int _a;
};
class com_real : public com
{
public:
void fill()
{ _a = std::min((float)_x, _y); }
protected:
float _a;
};
class happy_int : public com_int
{
public:
void smile() { _a ++; } // BAD: Will be duplicated
};
class happy_float : public com_real
{
public:
void smile() { _a ++; } // BAD: Duplicated code
}
class sad_int : public com_int
{
public:
frown() { _a --; }
}
Also, does anybody know a good book that teaches how to actually design code in C++ using OOP and template principles?
You can inherit from another helper template:
template <typename T, typename Derived> struct filler
{
T _a;
void fill()
{
com & b = static_cast<Derived&>(*this);
_a = std::min(b._x, b._y);
}
};
Usage:
struct com_int : com, filler<int, com_int> { };