当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C++ std::is_same模板用法及代码示例


<type_traits>头文件中提供了C++ STL的std::is_same模板。 C++ STL的std::is_same模板用于检查类型A是否与类型B相同。如果两者相同,则返回布尔值true,否则返回false。

头文件:

#include<type_traits>

模板类别:

template <class A, class B>
struct is_same

template <class A, class B>
inline constexpr 
       bool is_same_v
         = is_same<A, B>::value

用法:

std::is_same<A, B>::value

参数:此std::is_same模板接受以下参数:



  • A:它代表第一种类型。
  • B:它代表第二种类型。

返回值:模板std::is_same返回一个布尔变量,如下所示:

  • True:如果类型A与类型B相同。
  • False:如果类型A与类型B不同。

下面是在C++中演示std::is_same的程序:

程序:

// C++ program to illustrate std::is_same 
#include <bits/stdc++.h> 
#include <type_traits> 
using namespace std; 
  
// Driver Code 
int main() 
{ 
  
    cout << boolalpha; 
  
    cout << "is int & int32_t is same? "
         << is_same<int, int32_t>::value 
         << endl; 
  
    cout << "is int & int64_t is same? "
         << is_same<int, int64_t>::value 
         << endl; 
  
    cout << "is float & int32_t is same? "
         << is_same<float, int32_t>::value 
         << endl; 
  
    cout << "is int & int is same? "
         << is_same<int, int>::value << endl; 
    cout << "is int & unsigned int is same? "
         << is_same<int, unsigned int>::value 
         << endl; 
  
    cout << "is int & signed int is same? "
         << is_same<int, signed int>::value 
         << endl; 
  
    return 0; 
}
输出:
is int & int32_t is same? true
is int & int64_t is same? false
is float & int32_t is same? false
is int & int is same? true
is int & unsigned int is same? false
is int & signed int is same? true

程序2:

// C++ program to illustrate std::is_same 
#include <bits/stdc++.h> 
#include <type_traits> 
using namespace std; 
  
typedef int integer_type; 
  
// Declare structures 
struct A { 
    int x, y; 
}; 
struct B { 
    int x, y; 
}; 
typedef A C; 
  
// Driver Code 
int main() 
{ 
  
    cout << boolalpha; 
  
    cout << "is_same:" << endl; 
    cout << "int, const int is_same:"
         << is_same<int, const int>::value 
         << endl; 
  
    cout << "int, integer_type is_same:"
         << is_same<int, integer_type>::value 
         << endl; 
  
    cout << "A, B is_same:"
         << is_same<A, B>::value 
         << endl; 
  
    cout << "A, C is_same:"
         << is_same<A, C>::value 
         << endl; 
  
    cout << "signed char, int8_t is_same:"
         << is_same<signed char, int8_t>::value 
         << endl; 
  
    return 0; 
}
输出:
is_same:
int, const int is_same:false
int, integer_type is_same:true
A, B is_same:false
A, C is_same:true
signed char, int8_t is_same:true

参考: http://www.cplusplus.com/reference/type_traits/is_same/




相关用法


注:本文由纯净天空筛选整理自bansal_rtk_大神的英文原创作品 std::is_same template in C++ with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。