📜  C++中的std :: is_same模板及其示例

📅  最后修改于: 2021-05-30 08:44:49             🧑  作者: Mango

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

头文件:

#include

模板类别:

template 
struct is_same

template 
inline constexpr 
       bool is_same_v
         = is_same::value

句法:

std::is_same::value

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

  • 答:代表第一种。
  • B:代表第二种。

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

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

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

程序:

// C++ program to illustrate std::is_same
#include 
#include 
using namespace std;
  
// Driver Code
int main()
{
  
    cout << boolalpha;
  
    cout << "is int & int32_t is same? "
         << is_same::value
         << endl;
  
    cout << "is int & int64_t is same? "
         << is_same::value
         << endl;
  
    cout << "is float & int32_t is same? "
         << is_same::value
         << endl;
  
    cout << "is int & int is same? "
         << is_same::value << endl;
    cout << "is int & unsigned int is same? "
         << is_same::value
         << endl;
  
    cout << "is int & signed int is same? "
         << is_same::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 
#include 
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::value
         << endl;
  
    cout << "int, integer_type is_same: "
         << is_same::value
         << endl;
  
    cout << "A, B is_same: "
         << is_same::value
         << endl;
  
    cout << "A, C is_same: "
         << is_same::value
         << endl;
  
    cout << "signed char, int8_t is_same: "
         << is_same::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++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”