is_integral
- C++ course
- Advanced
- Lesson 14/83
- 5 min
Learn type classification with is_integral and is_floating_point.
is_integral / is_floating_point
std::is_integral_v<T> asks whether T is an integer type. It returns true for int, char, long and bool; false for double and std::string. std::is_floating_point_v<T> returns true for float and double.
These two traits classify numeric types. A template that wants different code per type first asks the trait and then branches with if constexpr. This is shorter than writing overloads.
Use with if constexpr
When a trait result feeds an if constexpr condition the compiler only instantiates the matching branch. Example: if constexpr (std::is_integral_v<T>) return x + 1; else return x; returns x + 1 for integers; for std::string that branch is not compiled.
This is useful to avoid writing overloads. A single template supports multiple types; for each type only the relevant branch is compiled. Trait + if constexpr is a core modern C++ pattern.
Practice Write the classify template
Write template <typename T> const char* classify(). The body should be if constexpr (std::is_integral_v<T>) return "int"; else return "other";. In main write std::cout << classify<int>();.
Starter code
#include <iostream>
#include <type_traits>
// Write the classify template
int main() {
// Call classify<int>() and print
return 0;
}Sample solution
#include <iostream>
#include <type_traits>
template <typename T>
const char* classify() {
if constexpr (std::is_integral_v<T>) return "int";
else return "other";
}
int main() {
std::cout << classify<int>();
return 0;
}Expected output
int
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the floating trait
template <typename T>
constexpr bool is_num = std::is_integral_v<T> || std::____<T>;
template <typename T>
constexpr bool is_num = std::is_integral_v<T> || std::is_floating_point_v<T>;
Explanation: is_floating_point_v<T> detects floating types.
2 What does is_integral_v<std::string> return?
std::is_integral_v<std::string>- true
- false Correct answer
- Compile error
- std::string
Explanation: std::string is not an integer type; the result is false.
3 Match the type to its trait
| Term | Meaning |
|---|---|
is_integral_v<int> |
true (integer) |
is_floating_point_v<int> |
false (not integer) |
is_integral_v<double> |
false (not floating) |
is_floating_point_v<double> |
true (floating) |