std::is_same<T, int>::value
is a type trait in C++ template metaprogramming, used to determine T
whether the type int
is the same as the type . Its return value is a constant expression of Boolean type, which has been determined when the template is instantiated, and it can be used for conditional compilation or selective compilation of types.
The returned value is returned when T
and int
are of the same type , otherwisestd::is_same<T, int>::value
true
false
.
For example, suppose you have the following code:
#include <type_traits>
template<typename T>
void foo(T value) {
if (std::is_same<T, int>::value) {
// 如果 T 的类型是 int,则执行此处的代码
// ...
}
else {
// 否则执行这里的代码
// ...
}
}
In this code example, if foo
the parameter type passed when calling the function is , the code in the branch int
will be executed ; if the parameter type is not, the code in the branch will be executed .if
int
else
std::is_same<T, int>::value
It is one of the type features introduced by C++11. They are all defined in <type_traits>
the header file and provide the function of querying and converting C++ types during compilation. std::is_same
The trait also has an alias: std::is_same_v<T, int>
, which is easier to use and can be used in C++17 and later.