2013-01-12 48 views
20

如何將僅接受數字類型(intdoublefloat等)的類模板編寫爲模板?數字類型的類模板

+0

@KonradRudolph待辦事項你還想修復標題?我很困惑,如果OP真的意味着類型或實際上意味着這些類型的常量。 – pmr

+0

@pmr我沒有(但我現在做),很好。我相當肯定,OP意味着類型,如果沒有其他原因,您不能將非整型類型用作非類型模板,並且在討論非類型模板時該問題沒有任何意義。 –

+0

@KonradRudolph是的,我的意思是類型。 – djWann

回答

26

您可以使用std::is_arithmetic類型特徵。如果你想只啓用一個類的實例這樣的類型,結合使用它std::enable_if

#include <type_traits> 

template< 
    typename T, //real type 
    typename = typename std::enable_if<std::is_arithmetic<T>::value, T>::type 
> struct S{}; 

int main() { 
    S<int> s; //compiles 
    S<char*> s; //doesn't compile 
} 

對於一個版本的enable_if這是更容易使用,以及免費添加disable_if,我極力推薦閱讀this wonderful article(或cached version)。

+2

您可以忽略'typename Dummy ='。此外,我強烈推薦在這裏使用[Wheels](https://bitbucket.org/martinhofernandes/wheels),它使代碼變得非常簡單:'template >>' –

+0

@ KonradRudolph,你是對的,謝謝。我會添加一個鏈接到他的'enable_if'文章作進一步閱讀。 – chris

+0

@KonradRudolph,刪除'Dummy'就是使它不能編譯,但我對它沒有太多經驗,所以我不能說它應該如何,除此之外。不過,我意識到我可以刪除無意義的名字。 – chris

3

,我發現,template<typename T, typename = ...>方法非常隱祕(VS 2015年)收到錯誤消息,但發現,與同類型性狀的static_assert也適用,讓我指定的錯誤消息:

#include <type_traits> 

template <typename NumericType> 
struct S 
{ 
    static_assert(std::is_arithmetic<NumericType>::value, "NumericType must be numeric"); 
}; 

template <typename NumericType> 
NumericType add_one(NumericType n) 
{ 
    static_assert(std::is_arithmetic<NumericType>::value, "NumericType must be numeric"); 
    return n + 1; 
} 

int main() 
{ 
    S<int> i; 
    S<char*> s; //doesn't compile 

    add_one(1.f); 
    add_one("hi there"); //doesn't compile 
} 
+0

當然。在這裏添加這條信息會很好。 – kyb