避免C++中继承层次结构中的重复代码
Avoid duplicated code in inheritance hierarchy in C++
我在一个继承层次结构中遇到了一些重复代码的问题。如何避免重复函数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> { };
相关文章:
- 如何重构类层次结构以避免菱形问题
- C++ 中模板化类型的类层次结构
- 为什么不同类型层次结构的指针之间的dynamic_cast定义得很好?
- 继承层次结构并将元素添加到向量
- C++ 类层次结构中的"对齐"是什么意思?
- 相同的层次结构,访问基类的受保护成员时的行为不同
- 类层次结构中的运算符重载
- 如何在层次结构中实现运算符使用?
- 反向层次结构中的可变参数模板参数
- 如何在继承层次结构中调用具有默认参数的构造函数?
- C++ 提升 - 包含类层次结构对象的类的序列化
- 在C++继承层次结构时提取实现者
- 在C++中将类实例添加到对象层次结构中的问题
- 确定大层次结构中基本指针的实际类型,无需dynamic_cast
- 在继承层次结构中复制和移动
- 模板冲突的类型-但类型应该是相同的cfr类层次结构
- 我们可以在层次结构中创建多个纯虚拟接口及其实现而不会代码爆炸吗?
- 我是否可以在类似于 C# 的 C++ 中创建全局命名空间层次结构,以帮助开发人员使用我们的代码?
- 避免C++中继承层次结构中的重复代码
- 避免类层次结构中的冗余代码