[英]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() {/* ... */ }
};
然后,我看到兩個選擇(至少,從我的觀點來看,它們幾乎是等效的):
使AllocFactorLinear
和AllocFactorScientific
私自從此類繼承,並using
指令將要公開的成員函數帶入范圍:
class AllocFactorLinear : CommonImpl { public: using CommonImpl::doSomething; };
聚合AllocFactorLinear
和AllocFactorScientific
的實現類, 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.