C++ - std::type_identity_t
std::type_identity_t
was introduced in C++20. Main purpose of this type alias has the following reasons.
- In C++, when you pass types around (especially templates), the compiler sometimes changes them automatically (for example, arrays decay to pointers, references collapse, qualifiers get lost).
- std::type_identity_t preserves the type exactly as it is.
- It also delays type deduction — making the compiler treat something as if it doesn’t know yet what the final type will be — useful in advanced template programming.
1
2
3
4
5
6
7
8
template <typename T>
void foo(T)
template <typename T>
void bar(std::type_identity_t<T>);
foo(5); // T is deduced to be int
bar(5); // Error: cannot deduce T
We need to specify the type explicitly for bar
1
bar<int>(5); // OK