Summary - Type traits
- C++ course
- Advanced
- Lesson 18/83
- 5 min
Combine is_integral, enable_if and conditional to write a generic function.
Summary - Type traits
In this group you met five tools of type traits: classification with std::is_integral_v, SFINAE constraints with std::enable_if_t, compile-time type selection with std::conditional_t, normalization with std::decay_t and reference-only stripping with std::remove_reference_t. All work at compile time.
Together these tools control which types a template accepts and produce different code per type. Now you will write a small task that combines what you learned.
Practice WideType summary
Write template <typename T> using WideType = std::conditional_t<std::is_integral_v<T>, long, double>;. In main write std::cout << std::is_same_v<WideType<int>, long>;.
Starter code
#include <iostream>
#include <type_traits>
// Write the WideType alias
int main() {
// Print the result
return 0;
}Sample solution
#include <iostream>
#include <type_traits>
template <typename T>
using WideType = std::conditional_t<std::is_integral_v<T>, long, double>;
int main() {
std::cout << std::is_same_v<WideType<int>, long>;
return 0;
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which tool selects a type at compile time?
- std::is_integral_v
- std::conditional_t Correct answer
- std::decay_t
- std::enable_if_t
Explanation: std::conditional_t<C, A, B> picks A or B at compile time.
2 Match each tool to its purpose
| Term | Meaning |
|---|---|
std::is_integral_v<T> |
Type classification |
std::enable_if_t<cond> |
SFINAE constraint |
std::conditional_t<C, A, B> |
Type selection |
std::decay_t<T> |
Type normalization |
3 Complete the conditional line
template <typename T>
using WideType = std::____<std::is_integral_v<T>, long, double>;
template <typename T>
using WideType = std::conditional_t<std::is_integral_v<T>, long, double>;
Explanation: conditional_t<C, A, B> selects a type at compile time.