繁体   English   中英

重构类

[英]Refactoring a class

我有两个几乎完全相同的类,实际上每个成员函数都相同,每个成员都相同,每个成员函数都做完全相同的事情。 这些类之间的唯一区别是我可以定义其类型的变量的方式:

AllocFactorScientific<102,-2> scientific;
AllocFactorLinear<1.2> linear;  

这是它们的标题:

template<double&& Factor>
struct AllocFactorLinear;

template<short Mantissa, short Exponent, short Base = 10>
struct AllocFactorScientific

我的问题是如何从那些类中重构那些函数,使我只能拥有一组函数,而不能拥有两组相同的函数。

提取第三类中的所有常见行为(为了清楚起见,我在答案中省略了模板参数):

class CommonImpl
{
public:
  void doSomething() {/* ... */ }
};

然后,我看到两个选择(至少,从我的观点来看,它们几乎是等效的):

  • 使AllocFactorLinearAllocFactorScientific 私自从此类继承,并using指令将要公开的成员函数带入范围:

     class AllocFactorLinear : CommonImpl { public: using CommonImpl::doSomething; }; 
  • 聚合AllocFactorLinearAllocFactorScientific的实现类, AllocFactorLinear所有调用转发给私有实现:

     class AllocFactorLinear { public: void doSomething() { impl_.doSomething(); } private: CommonImpl impl_; }; 

我个人会寻求第一个解决方案。

也许尝试使用此函数创建一些基类,并使用有关此基类继承的模板来完成这两个类。

为什么为此使用模板化类? 您能否将未模板化的类与2个不同的构造函数一起使用?

我认为应该是这样的:

template <typename Type>
struct AllocFactor {...};

然后可以输入Type ,例如:

template <double&& Factor>
struct LinearConfig
{
    static double value() { return Factor;}
};

和:

template <short Mantissa, short Exponent, short Base = 10>
struct FactorScientificConfig
{
    static double value() 
    {
       return some_expression_to_get_factor;
    }
};

您可以创建AllocFactor使用AllocFactor<LinearConfig<1.2>> ,并与相应的FactorScientificConfig 然后,您可以使用静态成员函数返回为两个类计算的值,以便AllocFactor<T>可以使用T::value()作为config类报告的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM