名稱空間
變體
操作

std::is_same

來自 cppreference.com
< cpp‎ | 型別
 
 
超程式設計庫
型別特性
型別類別
(C++11)
(C++11)(DR*)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11) 
(C++11)
(C++11)
型別屬性
(C++11)
(C++11)
(C++14)
(C++11)(C++26 中已棄用)
(C++11)(直到 C++20*)
(C++11)(C++20 中已棄用)
(C++11)
型別特性常量
元函式
(C++17)
支援的操作
關係與屬性查詢
型別修改
(C++11)(C++11)(C++11)
型別轉換
(C++11)(C++23 中已棄用)
(C++11)(C++23 中已棄用)
(C++11)
(C++11)(直到 C++20*)(C++17)

(C++11)
(C++17)
編譯時有理數算術
編譯時整數序列
 
定義於標頭檔案 <type_traits>
template< class T, class U >
struct is_same;
(C++11 起)

TU 指代同一型別(考慮 const/volatile 限定),則提供等於 true 的成員常量 value。否則 valuefalse

滿足交換律,即對於任意兩個型別 TU,當且僅當 is_same<U, T>::value == true 時,is_same<T, U>::value == true

如果程式為 std::is_samestd::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
[靜態]
TU 是同一型別,則為 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) 獲取表示式或實體的型別[編輯]