std::is_same
來自 cppreference.com
定義於標頭檔案 <type_traits> |
||
template< class T, class U > struct is_same; |
(C++11 起) | |
若 T
和 U
指代同一型別(考慮 const/volatile 限定),則提供等於 true 的成員常量 value。否則 value 為 false。
滿足交換律,即對於任意兩個型別 T
和 U
,當且僅當 is_same<U, T>::value == true 時,is_same<T, U>::value == true。
如果程式為 std::is_same
或 std::is_same_v
(C++17 起) 新增特化,則行為未定義。
目錄 |
[編輯] 輔助變數模板
template< class T, class U > constexpr bool is_same_v = is_same<T, U>::value; |
(C++17 起) | |
繼承自 std::integral_constant
成員常量
value [靜態] |
若 T 和 U 是同一型別,則為 true,否則為 false(public static 成員常量) |
成員函式
operator bool |
將物件轉換為 bool,返回 value (公開成員函式) |
operator() (C++14) |
返回 value (公開成員函式) |
成員型別
型別 | 定義 |
value_type
|
bool |
型別
|
std::integral_constant<bool, value> |
[編輯] 可能的實現
template<class T, class U> struct is_same : std::false_type {}; template<class T> struct is_same<T, T> : std::true_type {}; |
[編輯] 示例
執行此程式碼
#include <cstdint> #include <iostream> #include <type_traits> int main() { std::cout << std::boolalpha; // some implementation-defined facts // usually true if 'int' is 32 bit std::cout << std::is_same<int, std::int32_t>::value << ' '; // maybe true // possibly true if ILP64 data model is used std::cout << std::is_same<int, std::int64_t>::value << ' '; // maybe false // same tests as above, except using C++17's std::is_same_v<T, U> format std::cout << std::is_same_v<int, std::int32_t> << ' '; // maybe true std::cout << std::is_same_v<int, std::int64_t> << '\n'; // maybe false // compare the types of a couple variables long double num1 = 1.0; long double num2 = 2.0; static_assert( std::is_same_v<decltype(num1), decltype(num2)> == true ); // 'float' is never an integral type static_assert( std::is_same<float, std::int32_t>::value == false ); // 'int' is implicitly 'signed' static_assert( std::is_same_v<int, int> == true ); static_assert( std::is_same_v<int, unsigned int> == false ); static_assert( std::is_same_v<int, signed int> == true ); // unlike other types, 'char' is neither 'unsigned' nor 'signed' static_assert( std::is_same_v<char, char> == true ); static_assert( std::is_same_v<char, unsigned char> == false ); static_assert( std::is_same_v<char, signed char> == false ); // const-qualified type T is not same as non-const T static_assert( !std::is_same<const int, int>() ); }
可能的輸出
true false true false
[編輯] 另見
(C++20) |
指定型別與另一型別相同 (概念) |
decltype 說明符(C++11) |
獲取表示式或實體的型別 |