2016-09-03 59 views
1

我有這樣的代碼(「飛船」類運算符)。如何正確刪除模板函數中的代碼重複

template <class T> 
int comparator(const T &a, const T &b){ 
    if (a < b){ 
     return -1; 
    }else if (a > b){ 
     return +1; 
    } 

    return 0; 
} 

inline int comparator(const char *a, const char *b){ 
    return strcmp(a, b); // I never tried this, included just to get the idea 
} 

inline int comparator(char const a, char const b){ 
    return a - b; 
} 

inline int comparator(int const a, int const b){ 
    return a - b; 
} 

如何輕鬆刪除多個簽名類型(char,short,int,long等)的重複。我嘗試過SFINAE,但結果並不令人鼓舞。

+2

安置自己取這個與SFINAE。 – LogicStuff

+0

我無法正確編譯它 – Nick

回答

2

您可以混合在一起超載,標籤調度和模板,如下面的例子:

#include<type_traits> 
#include<utility> 
#include<iostream> 

template <class T> 
int comparator_(char, const T &a, const T &b){ 
    std::cout << "catch all" << std::endl; 
    return (a<b)?-1:((a>b)?1:0); 
} 

template<typename T> 
std::enable_if_t<std::is_same<T,int>::value or std::is_same<T,char>::value, int> 
comparator_(int, T const a, T const b){ 
    std::cout << "char or int" << std::endl; 
    return a - b; 
} 

template<typename... A> 
int comparator(A&&... args) { 
    return comparator_(0, std::forward<A>(args)...); 
} 

int main() { 
    comparator(42,0); 
    comparator('c', 'g'); 
    comparator(42u, 0u); 
} 
+1

是enable_if行上合法C++的「or」嗎?我以前從來沒有見過。 – SCFrench

+0

比較器_()的第一個參數是什麼原因 – Nick

+0

@SCFrench'或'和'和'分別是''''和'&&'的有效C++。 –

1

開始通過委託模板函數模板類

template <class T> 
int comparator(const T &a, const T &b){ 
    return comparator_impl<T>::comparator(a, b); 
} 

默認模板類的實現是什麼,你已經寫:

template<class T> 
class comparator_impl { 

public: 
    static int comparator(const T &a, const T &b){ 
     if (a < b){ 
      return -1; 
     }else if (a > b){ 
      return +1; 
     } 

    return 0; 
}; 

現在,有將要使用一個單獨的模板類對於有符號整型:

template<class T> 
class signed_int_comparator_impl { 

public: 
    static int comparator(T a, T b) 
    { 
      return a-b; 
    } 
    return 0; 
}; 

而現在,specia取得第一個模板類,繼承第二個模板類:

template<> 
class comparator_impl<char> : public signed_int_comparator_impl<char> {}; 

template<> 
class comparator_impl<int> : public signed_int_comparator_impl<int> {}; 

對剩餘的有符號整數類型進行泡沫,漂洗,重複。

如果你想專門0​​爲const char *,請隨時這樣做。