Namespaces
Variants

std:: is_same

From cppreference.net
Metaprogramming library
Type traits
Type categories
(C++11)
(C++11) ( DR* )
Type properties
(C++11)
(C++11)
(C++14)
(C++11) (deprecated in C++26)
(C++11) ( until C++20* )
(C++11) (deprecated in C++20)
(C++11)
Type trait constants
Metafunctions
(C++17)
Supported operations
Relationships and property queries
Type modifications
Type transformations
(C++11) (deprecated in C++23)
(C++11) (deprecated in C++23)
(C++11)
(C++11) ( until C++20* ) (C++17)

Compile-time rational arithmetic
Compile-time integer sequences
定义于头文件 <type_traits>
template < class T, class U >
struct is_same ;
(C++11 起)

如果 T U 命名相同的类型(考虑 const/volatile 限定符),则提供成员常量 value 等于 true 。否则 value false

满足交换律,即对于任意两个类型 T U is_same < T, U > :: value == true 当且仅当 is_same < U, T > :: 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
[static]
T U 为相同类型则为 true ,否则为 false
(公开静态成员常量)

成员函数

operator bool
转换对象为 bool 类型,返回 value
(公开成员函数)
operator()
(C++14)
返回 value
(公开成员函数)

成员类型

类型 定义
value_type bool
type 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>
#define SHOW(...) std::cout << #__VA_ARGS__ << " : " << __VA_ARGS__ << '\n'
int main()
{
    std::cout << std::boolalpha;
    // 一些实现定义的事实
    // 若 'int' 为32位通常为真
    SHOW( std::is_same<int, std::int32_t>::value ); // 可能为真
    // 若使用ILP64数据模型可能为真
    SHOW( std::is_same<int, std::int64_t>::value ); // 可能为假
    // 与上述测试相同,但使用C++17的std::is_same_v<T, U>格式
    SHOW( std::is_same_v<int, std::int32_t> ); // 可能为真
    SHOW( std::is_same_v<int, std::int64_t> ); // 可能为假
    // 比较几个变量的类型
    long double num1 = 1.0;
    long double num2 = 2.0;
    static_assert( std::is_same_v<decltype(num1), decltype(num2)> == true );
    // 'float' 永远不是整型
    static_assert( std::is_same<float, std::int32_t>::value == false );
    // 'int' 隐式为 '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 );
    // 与其他类型不同,'char' 既非 'unsigned' 也非 '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限定类型T与非const T不同
    static_assert( !std::is_same<const int, int>() );
}
#undef SHOW

可能的输出:

std::is_same<int, std::int32_t>::value : true
std::is_same<int, std::int64_t>::value : false
std::is_same_v<int, std::int32_t> : true
std::is_same_v<int, std::int64_t> : false

参见

(C++20)
指定一个类型与另一个类型相同
(概念)
decltype specifier (C++11) 获取表达式或实体的类型