std::is_same

定义于头文件 <type_traits>
template< class T, class U >
struct is_same;
(C++11 起)

TU 指名拥有同一 const-volatile 限定的相同类型,则提供等于 true 的成员常量 value 。否则 valuefalse

目录

帮助变量模板

template< class T, class U >
inline constexpr bool is_same_v = is_same<T, U>::value;
(C++17 起)

继承自 std::integral_constant

成员常量

value
[静态]
TU 是同一类型则为 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 <iostream>
#include <type_traits>
#include <cstdint>
 
void print_separator()
{
    std::cout << "-----\n";
}
 
int main()
{
    std::cout << std::boolalpha;
 
    std::cout << std::is_same<int, int32_t>::value << '\n';   // true
    std::cout << std::is_same<int, int64_t>::value << '\n';   // false
    std::cout << std::is_same<float, int32_t>::value << '\n'; // false
 
    print_separator();
 
    std::cout << std::is_same<int, int>::value << "\n";          // true
    std::cout << std::is_same<int, unsigned int>::value << "\n"; // false
    std::cout << std::is_same<int, signed int>::value << "\n";   // true
 
    print_separator();
 
    // unlike other types 'char' is not 'unsigned' and not 'signed'
    std::cout << std::is_same<char, char>::value << "\n";          // true
    std::cout << std::is_same<char, unsigned char>::value << "\n"; // false
    std::cout << std::is_same<char, signed char>::value << "\n";   // false
}

输出:

true
false
false
-----
true
false
true
-----
true
false
false

参阅

(C++11)
检查类型是否为整型
(类模板)
(C++11)
将整数类型转换成对应的有符号整数类型
(类模板)
将整数类型转换成对应的无符号整数类型
(类模板)

版本历史

  • (当前 | 先前 2017年7月8日 (六) 09:42Fruderica讨论 | 贡献. . (2,004字节) (+620). . (撤销)
  • 当前 | 先前 2014年10月26日 (日) 18:15P12bot讨论 | 贡献 . . (1,384字节) (0). . (Fix some translations) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:42P12bot讨论 | 贡献 . . (1,384字节) (-54). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 16:02P12bot讨论 | 贡献 . . (1,438字节) (+201). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月27日 (六) 11:49P12讨论 | 贡献 . . (1,237字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 06:00TranslationBot讨论 | 贡献. . (1,237字节) (-21). . (Translated from the English version using Google Translate) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:33P12讨论 | 贡献 . . (1,258字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,258字节) (+1,258). . (Translated from the English version using Google Translate)