What are type traits?
- C++ course
- Advanced
- Lesson 13/83
- 5 min
Learn to query type information with type traits.
What are type traits?
Type traits are templates that give information about types at compile time. They live in the <type_traits> header. std::is_integral<T>::value is a bool constant that is true when T is an integer type and false otherwise.
Traits drive branching, type selection and constraints in templates. The C++17 _v shortcut returns the value directly: std::is_integral_v<T> equals std::is_integral<T>::value. All results are computed at compile time.
_v and ::value
A trait result is read in two ways. Classic: std::is_integral<T>::value. C++17 shortcut: std::is_integral_v<T>. Both yield the same bool constant; the shortcut simply saves typing.
Similarly std::conditional<C, A, B>::type becomes std::conditional_t<C, A, B>. _v is for values, _t is for types. These shortcuts are the standard way to write readable template code.
Practice Write the IsIntTag template
Write template <typename T> struct IsIntTag with static const bool value = std::is_integral_v<T>; inside. In main write std::cout << IsIntTag<int>::value;.
Starter code
#include <iostream>
#include <type_traits>
// Write the IsIntTag template
int main() {
// Print the result
return 0;
}Sample solution
#include <iostream>
#include <type_traits>
template <typename T>
struct IsIntTag {
static const bool value = std::is_integral_v<T>;
};
int main() {
std::cout << IsIntTag<int>::value;
return 0;
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When are type traits evaluated?
- At compile time Correct answer
- At run time
- At link time
- At load time
Explanation: Type traits are computed at compile time.
2 Complete the trait shortcut
template <typename T>
constexpr bool is_int = std::____<T>;
template <typename T>
constexpr bool is_int = std::is_integral_v<T>;
Explanation: is_integral_v<T> is a compile-time bool constant.
3 Match each trait to its purpose
| Term | Meaning |
|---|---|
std::is_integral_v<T> |
Is integer? |
std::is_floating_point_v<T> |
Is floating? |
std::is_pointer_v<T> |
Is pointer? |
std::is_class_v<T> |
Is class? |