The*_* do 5 c++ refactoring c++11
我有两个几乎相同的类,实际上每个成员函数都是相同的,每个成员都是相同的,每个成员函数都完全相同.这些类之间的唯一区别是我可以定义其类型变量的方式:
AllocFactorScientific<102,-2> scientific;
AllocFactorLinear<1.2> linear;
Run Code Online (Sandbox Code Playgroud)
这是他们的标题:
template<double&& Factor>
struct AllocFactorLinear;
template<short Mantissa, short Exponent, short Base = 10>
struct AllocFactorScientific
Run Code Online (Sandbox Code Playgroud)
我的问题是如何从那些允许我只有一组函数而不是两组相同函数的类中重构那些函数.
提取第三类中的所有常见行为(为了清楚起见,我在答案中省略了模板参数):
class CommonImpl
{
public:
void doSomething() {/* ... */ }
};
Run Code Online (Sandbox Code Playgroud)
然后我看到两个选择(至少从我的角度来看,它们几乎是等效的):
创建AllocFactorLinear并从此类私有AllocFactorScientific继承,并使用指令将您希望在范围内公开的成员函数引入:using
class AllocFactorLinear : CommonImpl
{
public:
using CommonImpl::doSomething;
};
Run Code Online (Sandbox Code Playgroud)将实现类聚合在AllocFactorLinear和中AllocFactorScientific,并将所有调用转发到私有实现:
class AllocFactorLinear
{
public:
void doSomething() { impl_.doSomething(); }
private:
CommonImpl impl_;
};
Run Code Online (Sandbox Code Playgroud)我个人会选择第一个解决方案。