Card 1 / 7
A type trait is a class template whose instantiation is the answer. This one takes two types and reports whether they are exactly the same type — no conversions, no decay, no ignoring const.
T |
U |
is_same_type<T, U>::value |
|---|---|---|
int |
int |
true |
double* |
double* |
true |
int |
double |
false |
int |
const int |
false |
int |
int& |
false |
Two declarations. The primary template takes class T, class U and inherits std::bool_constant<false>; the partial specialization writes the same parameter twice in the argument list — struct is_same_type<T, T> — so it only matches when the compiler can bind one T to both, and inherits std::bool_constant<true>.
Inheriting is what supplies the static constexpr bool value member; you never declare value yourself.
// Write a trait that reports whether two types are exactly the same type.
//
// std::bool_constant<B> is the library's carrier for a compile-time bool: it
// publishes a static constexpr bool value equal to B. Inherit from it.
//
// 1. a primary template taking two types, answering false
// 2. a partial specialization for the case where both arguments are the
// SAME type, answering true
template <class T, class U>
struct is_same_type : std::bool_constant<false> {};
template <class T>
struct is_same_type<T, T> : std::bool_constant<true> {};Card 2 / 7
A compile-time if for types: given a bool known at compile time, name one type or the other. The primary template already covers the true case; the false case is a partial specialization on the value of the non-type parameter.