2013-05-03 42 views
0

如何爲特定類型約束制定static_assert如何C++ 11 static_assert類型約束?

目前我只想讓我的模板僅適用於unsigned int類型,但不適用於signed int類型。或者,僅用於整數類型或特定類型名稱。 static_assert(sizeof(int))只提供基於大小的斷言,我不知道如何執行任何額外的檢查。

我在Xcode 4.6.2中使用Clang及其libc++。以下是命令行上的當前編譯器信息。

Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn) 
Target: x86_64-apple-darwin12.3.0 
Thread model: posix 
+0

注意 - 這是可能的類型約束列表:http://www.cplusplus.com/reference/type_traits/ – Eonil 2013-05-03 02:05:17

回答

4

這算不上什麼static_assert是,但你可以做這樣的:

template<typename T> 
struct Type 
{ 
    static_assert(std::is_same<T, unsigned int>::value, "bad T"); 
}; 

或者,如果你只是想T是一個無符號整型某種(沒有具體unsigned int ):

template<typename T> 
struct Type 
{ 
    static_assert(std::is_unsigned<T>::value, "bad T"); 
}; 
+0

static_assert需要一個字符串第二個參數 - 我繼續添加它們,所以沒有人引起輕微的誤入歧途。 :-) – 2013-09-06 21:31:16

1

這裏有一個支架:

#include <type_traits> 

template<typename TNum> 
struct WrapNumber 
{ 
    static_assert(std::is_unsigned<TNum>::value, "Requires unsigned type"); 
    TNum num; 
}; 

WrapNumber<unsigned int> wui; 
WrapNumber<int> wi; 
0

要檢查所有整數類型,下面就可以使用:

#include <type_traits> 
// [...] 
static_assert(std::is_integral<T>::value, "The type T must be an integral type."); 
// [...]