2010-11-25 30 views
5

我有兩個幾乎完全相同的類,實際上每個成員函數都是相同的,每個成員都是相同的,每個成員函數都完全相同。這些類之間的唯一區別是我可以定義自己的類型變量的方式:重構類

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

這裏是頭對他們來說:

template<double&& Factor> 
struct AllocFactorLinear; 

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

我的問題是如何重構這些功能了這些類的這將允許我只有一組功能而不是兩組相同的功能。

回答

3

提取在第三類中的所有常見的行爲(我忽略我的回答模板參數爲清晰起見):

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

我再看看兩個選擇(這是從我的觀點來看至少,幾乎相當於):

  • AllocFactorLinearAllocFactorScientific繼承私下從這個類,併爲您帶來希望的範圍,暴露了0成員函數個指令:

    class AllocFactorLinear : CommonImpl 
    { 
    public: 
        using CommonImpl::doSomething; 
    }; 
    
  • 聚集在AllocFactorLinearAllocFactorScientific並轉發所有的呼叫私有實現的實現類:

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

我會親自去的第一個解決方案。

+0

是的,我在幾分鐘前就想到了類似的事情。謝謝。將與第一個選項一起去。 – 2010-11-25 22:04:35

2

也許嘗試用這個函數創建一些基類,然後用這個基類的繼承模板做這2個類。

0

爲什麼你使用模板類呢? 不能用2個不同構造函數的未定義類嗎?

0

我認爲這將是這樣的:

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>>和對應。然後,您可以使用靜態成員函數來返回爲這兩個類計算的值,以便AllocFactor<T>可以使用T::value()作爲config類所報告的值。