std::is_same
来自cppreference.com
<tbody>
</tbody>
| 在标头 <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 起) 的特化,那么行为未定义。
辅助变量模板
<tbody> </tbody> 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 (公开静态成员常量) |
成员函数
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 位则通常为 true
SHOW( std::is_same<int, std::int32_t>::value ); // 可能为 true
// 若使用 ILP64 数据模型则可能为 true
SHOW( std::is_same<int, std::int64_t>::value ); // 可能为 false
// 与上面相同的测试,但使用了 C++17 的 std::is_same_v<T, U> 格式
SHOW( std::is_same_v<int, std::int32_t> ); // 可能为 true
SHOW( std::is_same_v<int, std::int64_t> ); // 可能为 false
// 比较一对变量的类型
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 说明符(C++11)
|
获得表达式或实体的类型 |