<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/
相關用法
- C++ std::is_assignable模板用法及代碼示例
- C++ std::is_function模板用法及代碼示例
- C++ std::is_convertible模板用法及代碼示例
- C++ std::is_constructible模板用法及代碼示例
- C++ std::is_base_of模板用法及代碼示例
- C++ std::is_member_object_pointer模板用法及代碼示例
- C++ std::is_trivially_copyable模板用法及代碼示例
- C++ std::is_member_function_pointer模板用法及代碼示例
- C++ is_rvalue_reference用法及代碼示例
- C++ is_fundamental用法及代碼示例
注:本文由純淨天空篩選整理自bansal_rtk_大神的英文原創作品 std::is_same template in C++ with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。