Learn C++
#include "templates/type_traits.hpp"

Type Traits in C++

//concept

Type traits (<type_traits>) answer compile-time questions about types: std::is_integral<int>::value is true, std::is_pointer<float*>::value is true, std::remove_const<const int>::type is int. Built from template specialization, they let generic code adapt — choose algorithms, enable overloads, and assert assumptions without running anything.

Modern spelling uses _v/_t aliases (is_integral_v<T>, remove_const_t<T>) that skip the ::value/::type noise. Combined with if constexpr, traits branch generic code at compile time: one function, per-category implementations, zero run-time cost.

//how it works
1

Ask questions with _v

std::is_integral_v<T>, std::is_floating_point_v<T>, std::is_same_v<A, B> — boolean answers about any type, usable in static_assert and if constexpr.

2

Transform with _t

std::remove_const_t<T>, std::decay_t<T>, std::add_pointer_t<T> compute new types from old — the building blocks of generic utilities.

3

Branch with if constexpr

if constexpr (std::is_pointer_v<T>) compiles only the taken branch — per-category code paths inside one template, discarded branches never instantiated.

4

Specialization underneath

Every trait is primary-template-plus-specializations under the hood — custom traits for project types follow the same recipe.

//example
#include <iostream>
#include <type_traits>
 
template <typename T>
void describe() {
if constexpr (std::is_integral_v<T>) {
std::cout << "integer-like" << std::endl;
} else {
std::cout << "other" << std::endl;
}
}
Output
integer-like
other
1describe<int>() takes the true branch at compile time — the else branch is discarded, never compiled.
2describe<double>() takes the false branch instead, from the same single definition.
3Both lines print from per-type compile-time decisions with no run-time branching cost.
//use cases
Constraining and branching generic code per type category
static_assert verification of template assumptions with readable messages
Stripping qualifiers and decaying types in forwarding utilities
Writing custom traits for project-specific type vocabularies

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.