避免C++中继承层次结构中的重复代码

Avoid duplicated code in inheritance hierarchy in C++

本文关键字:代码 层次结构 C++ 继承 避免      更新时间:2023-10-16

我在一个继承层次结构中遇到了一些重复代码的问题。如何避免重复函数smile()中的代码?

鉴于变量_a在基类中不存在,我无法将函数移到那里。创建像template<typename T> void smile(T& a) { a++; }这样的模板函数对我来说并不是一个真正的解决方案。我的实际代码有点复杂,如果不是不可能应用于我当前的设计,这样的解决方案会非常混乱。

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 --; }
}

此外,有人知道一本好书,教你如何使用面向对象和模板原理在C++中实际设计代码吗?

您可以从另一个辅助模板继承:

template <typename T, typename Derived> struct filler
{
    T _a;
    void fill()
    {
        com & b = static_cast<Derived&>(*this);
        _a = std::min(b._x, b._y);
    }
};

用法:

struct com_int : com, filler<int, com_int> { };