2009-01-31 66 views
5

要專門化一個類模板,必須重新定義底層基本模板(即非專用類模板)中的所有成員函數,即使它們預計會保持大部分不變。什麼是一些被接受的方法和避免這種代碼重複的「最佳實踐」?關於模板專門化和產生的代碼複製的一個問題

謝謝。

回答

10

您可以完全專注一個部件選擇:

template<int N> 
struct Vector { 
    int calculate() { return N; } 
}; 

// put into the .cpp file, or make inline! 
template<> 
int Vector<3>::calculate() { return -1; } 

你做一個完整的專業化。這意味着你不能部分專門它:

template<int N, int P> 
struct Vector { 
    int calculate() { return N; } 
}; 

// WROOONG! 
template<int N> 
int Vector<N, 3>::calculate() { return -1; } 

如果需要,你可以使用enable_if:

template<int N, int P> 
struct Vector { 
    int calculate() { return calculate<P>(); } 
private: 
    // enable for P1 == 3 
    template<int P1> 
    typename enable_if_c<P1 == P && P1 == 3, int>::type 
    calculate() { return -1; } 

    // disable for P1 == 3 
    template<int P1> 
    typename enable_if_c<!(P1 == P && P1 == 3), int>::type 
    calculate() { return N; } 
}; 

另一種方法是共同的東西分割你的東西了(爲一個基類和專業像Nick建議的那樣。

我通常會採取第二種方法。但我更喜歡第一個,如果我不需要部分專門化的功能。

4

我通常在出現這種情況時使用了基類。即:將通用功能放在基類中,並從中派生模板類,然後專門化派生類,只使用不同的函數。

+0

有關更多詳細信息,請參閱Scott Meyers的「Effective C++,Third Edition」中的「項目44:因子參數無關的模板代碼」 – 2009-01-31 18:51:56