C++ Intermediate · Lesson 14 of 27
Type traits
std::is_same, std::is_integral, enable_if and compile-time type questions.
Estimated time · 45–75 min
Learning goals
What you will understand
- Explain type traits in your own words
- Use it in a small robotics example
- Verify the result instead of assuming it worked
Understand the idea first
The mental model
The <type_traits> header lets code ask questions about types at compile time: std::is_same_v<A, B>, std::is_integral_v<T>, std::is_floating_point_v<T>, std::is_pointer_v<T>. Each has a _v shortcut for the value and a _t shortcut for transformations such as std::remove_reference_t<T>.
Traits are used with static_assert (fail compilation with a message) and with if constexpr (choose code by type). They are the building blocks of generic code that you meet again in Phase 4.
Guided lesson
Work through these steps
- 1.
Read the type traits example and identify what each line owns or changes.
- 2.
Create a small source file, compile with -std=c++17 and warnings enabled, and run it.
- 3.
Change one input, predict the result before running, then compare the output.
- 4.
Record one compiler or runtime error and explain the correction in your own words.
Worked example
Read it before you run it
#include <type_traits>
// Header with the standard traits.
static_assert(std::is_integral_v<int>, "int is integral");
// Compile-time check: fails to compile if the statement is false.
static_assert(!std::is_integral_v<double>, "double is not integral");
// The opposite check.
static_assert(std::is_same_v<std::remove_reference_t<int&>, int>, "strip the reference");
// remove_reference_t turns int& into int.
template <typename T>
// Start a template so the function works for many types.
std::string describe(T value) {
// Return a description that depends on the type.
if constexpr (std::is_integral_v<T>) return "whole number";
// Chosen at compile time for int, long, etc.
else if constexpr (std::is_floating_point_v<T>) return "fraction";
// Chosen for float and double.
else return "something else";
// Fallback for all other types.
}
// End of describe.What the example is doing
- 1.Read declarations from right to left: identify each value's type, name, and initial value.
- 2.Follow the data through each expression before considering syntax shortcuts.
- 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.
Watch it run · Values in memory
See what this code does
The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.
Demo for Type traits. Expected result: whole number fraction
Practice code
Now type it yourself
Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice
#include <iostream>
#include <string>
#include <type_traits>
template <typename T>
std::string describe(T) {
// TODO: use if constexpr: is_integral_v -> "whole number", is_floating_point_v -> "fraction", otherwise "other"
}
int main() {
std::cout << describe(3) << '\n' << describe(2.5) << '\n';
return 0;
}Expected output
whole number
fractionStuck? Show the full solution (try it yourself first)
#include <iostream>
#include <string>
#include <type_traits>
template <typename T>
std::string describe(T) {
if constexpr (std::is_integral_v<T>) return "whole number";
else if constexpr (std::is_floating_point_v<T>) return "fraction";
else return "other";
}
int main() {
std::cout << describe(3) << '\n' << describe(2.5) << '\n';
return 0;
}Expected result
How you know it worked
- After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
- Changing the stated input produces the result you predicted.
Practical exercise
Apply the lesson
Write a template scale(T value, double factor) that static_asserts std::is_arithmetic_v<T>. Call it with int and double, then with std::string and read the compiler message.
Before you continue
- The program builds with -std=c++17 and no warnings
- You can explain the key rule without reading the example
- The normal and edge cases both have recorded results
If something goes wrong
Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.
Print the inputs and intermediate values, then check conversions, units, and collection order.