std::is_signed
來自 cppreference.com
定義於標頭檔案 <type_traits> |
||
template< class T > struct is_signed; |
(C++11 起) | |
std::is_signed
是一個 一元型別特性 (UnaryTypeTrait)。
檢查 T
是否是有符號算術型別。
- 如果 std::is_arithmetic<T>::value 為 true,則提供成員常量
value
,其等於 T(-1) < T(0)。 - 否則,提供成員常量
value
,其等於 false。
如果程式為 std::is_signed
或 std::is_signed_v
新增特化,則行為未定義。
目錄 |
[編輯] 模板引數
T | - | 要檢查的型別 |
[編輯] 輔助變數模板
template< class T > constexpr bool is_signed_v = is_signed<T>::value; |
(C++17 起) | |
繼承自 std::integral_constant
成員常量
value [靜態] |
true 如果 T 是有符號算術型別,否則為 false(public static 成員常量) |
成員函式
operator bool |
將物件轉換為 bool,返回 value (公開成員函式) |
operator() (C++14) |
返回 value (公開成員函式) |
成員型別
型別 | 定義 |
value_type
|
bool |
型別
|
std::integral_constant<bool, value> |
[編輯] 可能的實現
namespace detail { template<typename T, bool = std::is_arithmetic<T>::value> struct is_signed : std::integral_constant<bool, T(-1) < T(0)> {}; template<typename T> struct is_signed<T, false> : std::false_type {}; } template<typename T> struct is_signed : detail::is_signed<T>::type {}; |
[編輯] 示例
執行此程式碼
#include <iostream> #include <type_traits> class A {}; static_assert(std::is_signed_v<A> == false); class B { int i; }; static_assert(std::is_signed_v<B> == false); enum C : int {}; static_assert(std::is_signed_v<C> == false); enum class D : int {}; static_assert(std::is_signed_v<D> == false); static_assert ( std::is_signed<signed int>::value == true and // C++11 std::is_signed<signed int>() == true and // C++11 std::is_signed<signed int>{} == true and // C++11 std::is_signed_v<signed int> == true and // C++17 std::is_signed_v<unsigned int> == false and std::is_signed_v<float> == true and std::is_signed_v<bool> == false and std::is_signed_v<signed char> == true and std::is_signed_v<unsigned char> == false ); int main() { // signedness of char is implementation-defined: std::cout << std::boolalpha << std::is_signed_v<char> << '\n'; }
可能的輸出
true
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 2197 | C++11 | value 可能為 true,即使 T 不是算術型別 |
在此情況下只能為 false |
[編輯] 參閱
(C++11) |
檢查型別是否為無符號算術型別 (類模板) |
[靜態] |
確定有符號型別 ( std::numeric_limits<T> 的公共靜態成員常量) |
(C++11) |
檢查型別是否為算術型別 (類模板) |
(C++11) |
獲取給定整型對應的有符號型別 (類模板) |
(C++11) |
獲取給定整型對應的有符號型別 (類模板) |