Motivation
Type traits provide a compile-time mechanism to query and manipulate properties of types using templates.
Example
Using type traits, we can write a template that behaves differently depending on whether a type is an integral type or not. For instance:
#include <type_traits>
#include <iostream>
template <typename>
void print_type_info(T value) {
if constexpr (std::is_integral<t>::value) {
std::cout << "Integral type: " << value << "\n";
} else {
std::cout << "Non-integral type: " << value << "\n";
}
}
int main() {
print_type_info(42); // Integral type
print_type_info(3.14); // Non-integral type
}
In this example, std::is_integral<T> is a type trait that tells us at compile time whether T is an integral type, enabling different behavior without runtime overhead.