std::is_same template in C++ with Examples
The std::is_same template of C++ STL is present in the <type_traits> header file. The std::is_same template of C++ STL is used to check whether the type A is same type as of B or not. It return the boolean value true if both are same, otherwise return false.
Header File:
#include<type_traits>
Template Class:
template <class A, class B> struct is_same template <class A, class B> inline constexpr bool is_same_v = is_same<A, B>::value
Syntax:
std::is_same<A, B>::value
Parameters: This std::is_same template accepts the following parameters:
- A: It represent the first type.
- B: It represent the second type.
Return Value: The template std::is_same returns a boolean variable as shown below:
- True: If the type A is same as the type B.
- False: If the type A is not same as the type B.
Below is the program to demonstrate std::is_same in C++:
Program:
// 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; } |
Output:
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
Program 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; } |
Output:
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
Reference: http://www.cplusplus.com/reference/type_traits/is_same/
Please Login to comment...