[英]A Question on Template Specialization and the Resulting Code Duplication
要專門化類模板,必須重新定義底層基本模板中的所有成員函數(即非專用類模板),即使它們預計基本保持不變。 有哪些可接受的方法和“最佳實踐”可以避免此代碼重復?
謝謝。
您可以選擇性地完全專門化成員:
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推薦的那樣。
我通常采取第二種方法。 但如果我不需要部分專門化功能,我更喜歡第一個。
通常在出現這種情況時我會使用基類。 即:將通用功能放在基類中,並從中派生模板類,然后使用不同的函數專門化派生類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.