C++C++ Explainer
C++ · 7 · Advanced / Job-Ready34 / 36 · 94%

type_traits, tuple & constexpr

Computation and introspection that finishes before the program starts.

Examples: is_same_v, tuple, constexpr, consteval

shortcuts: ← prev · → next · M mark
1

type_traits

Ask questions about types at compile time.

Example
example
#include <type_traits>

static_assert(std::is_integral_v<int>);
static_assert(!std::is_copy_constructible_v<std::unique_ptr<int>>);

using Bare = std::remove_cvref_t<const std::string&>;   // std::string
2

std::tuple

Heterogeneous fixed-size storage with compile-time indexing.

Example
example
std::tuple<int, std::string, double> row{1, "ada", 3.5};

auto& name = std::get<1>(row);
auto [id, n, score] = row;               // structured bindings

std::apply([](auto&&... xs){ (std::cout << ... << xs); }, row);
3

constexpr & consteval

Run real code at compile time.

Example
example
constexpr int factorial(int n) {
    return n <= 1 ? 1 : n * factorial(n - 1);
}
static_assert(factorial(5) == 120);      // computed by the compiler

consteval int must_be_compile_time(int n) { return n * 2; }
constinit int global = factorial(4);     // guaranteed static init
TIP
constexpr functions can also run at runtime; consteval functions cannot.
4

Compile-Time Cost

Metaprogramming is not free.

Common pitfalls
  • ✕Deep template recursion explodes compile time and memory.
  • ✕Prefer if constexpr and concepts over enable_if chains — far cheaper to compile and read.
  • ✕Every distinct instantiation adds code to the binary.