std::is_same

Defined in header <type_traits>
1
2
template< class T, class U >
struct is_same;
(since C++11)

If T and U name the same type with the same const-volatile qualifications, provides the member constant value equal to true. Otherwise value is false.

Helper variable template

1
2
template< class T, class U >
constexpr bool is_same_v = is_same<T, U>::value;
(since C++17)

Inherited from std::integral_constant

Member constants

value
[static]
true if T and U is the same type , false otherwise
(public static member constant)

Member functions

operator bool
converts the object to bool, returns value
(public member function)
operator()
(C++14)
returns value
(public member function)

Member types

Type Definition
value_type bool
type std::integral_constant<bool, value>

Possible implementation

1
2
3
4
5
template<class T, class U>
struct is_same : std::false_type {};
  
template<class T>
struct is_same<T, T> : std::true_type {};

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <type_traits>
#include <cstdint>
  
void print_separator()
{
    std::cout << "-----\n";
}
  
int main()
{
    std::cout << std::boolalpha;
  
    std::cout << std::is_same<int, int32_t>::value << '\n';   // true
    std::cout << std::is_same<int, int64_t>::value << '\n';   // false
    std::cout << std::is_same<float, int32_t>::value << '\n'; // false
  
    print_separator();
  
    std::cout << std::is_same<int, int>::value << "\n";          // true
    std::cout << std::is_same<int, unsigned int>::value << "\n"; // false
    std::cout << std::is_same<int, signed int>::value << "\n";   // true
  
    print_separator();
  
    // unlike other types 'char' is not 'unsigned' and not 'signed'
    std::cout << std::is_same<char, char>::value << "\n";          // true
    std::cout << std::is_same<char, unsigned char>::value << "\n"; // false
    std::cout << std::is_same<char, signed char>::value << "\n";   // false
}

Output:

1
2
3
4
5
6
7
8
9
10
11
true
false
false
-----
true
false
true
-----
true
false
false

See also

(C++11)
checks if a type is integral type
(class template)
(C++11)
makes the given integral type signed
(class template)
makes the given integral type unsigned
(class template)
std::experimental::is_same_v
(library fundamentals TS)
variable template alias of std::is_same::value
(variable template)
doc_CPP
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.