Skip to main content
Be Bitwise
C++Modern C++ Patterns

Metaprogramming

Metaprogramming in C++ means doing your computing at compile time so runtime doesn't have to. The compiler grinds through the work; your binary ships with the answer baked in. C++17 and C++20 dragged this dark art into daylight via constexpr, if constexpr, fold expressions, and concepts — most of it is now legible to mortals.

constexpr: Compile-Time Computation

A constexpr function can run at compile time, provided its arguments are themselves compile-time constants:

cpp
constexpr int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
// Computed at compile time
constexpr int f10 = factorial(10); // 3628800
// Used in templates and array sizes
std::array<int, factorial(5)> arr; // std::array<int, 120>

C++20 stretched constexpr to cover virtual functions, dynamic allocation via new/delete, and try/catch. Yes, even heap allocation at compile time:

cpp
constexpr std::vector<int> make_primes(int limit) {
std::vector<int> primes;
for (int n = 2; n < limit; n++) {
bool is_prime = true;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) { is_prime = false; break; }
}
if (is_prime) primes.push_back(n);
}
return primes;
}

There's a catch: memory allocated during constant evaluation has to be freed before that evaluation ends. constexpr auto n = make_primes(100).size(); compiles, because the vector dies inside the expression, but constexpr auto v = make_primes(100); doesn't. To keep the results, copy them into a std::array.

Key Concept

constexpr is a request, not a guarantee. The function only fires at compile time when its result lands in a constexpr context — initialising a constexpr variable, feeding a template argument, that sort of thing. In any other context the same function may quietly run at runtime.

The runner on this site compiles C++14, so if constexpr, folds and concepts won't build there. Relaxed constexpr functions and SFINAE are both C++14, though, and they're enough to watch the compiler do the arithmetic. The static_assert and the array size are worked out before the program exists. The runtime call isn't.

Try itChange 3628800 in the static_assert and the program stops building. Then uncomment the last old_add line and read the SFINAE error; a Numeric concept would name the failed requirement directly.
C++ (GCC 9.2.0)

if constexpr: Compile-Time Branching

if constexpr prunes branches at compile time. The branch the compiler throws away doesn't even need to be valid code for the type in hand — handy when one arm refers to a member another type lacks:

cpp
#include <type_traits>
#include <iostream>
#include <string>
// Dependent on T, so the static_assert only fires if this branch is instantiated
template <typename>
inline constexpr bool always_false = false;
template <typename T>
std::string to_string_generic(const T& value) {
if constexpr (std::is_arithmetic_v<T>) {
return std::to_string(value);
} else if constexpr (std::is_same_v<T, std::string>) {
return value;
} else if constexpr (std::is_same_v<T, const char*>) {
return std::string(value);
} else {
static_assert(always_false<T>, "Unsupported type");
}
}

Without if constexpr, that's template specialisation or SFINAE for each case. Both are routes most people would rather not walk.

Fold Expressions (C++17)

Fold expressions apply a binary operator across a parameter pack:

cpp
// Sum all arguments
template <typename... Args>
auto sum(Args... args) {
return (args + ...); // Right fold: a1 + (a2 + (a3 + ...))
}
int total = sum(1, 2, 3, 4, 5); // 15
// Print all arguments
template <typename... Args>
void print_all(Args&&... args) {
((std::cout << args << " "), ...);
std::cout << "\n";
}
print_all(1, "hello", 3.14); // "1 hello 3.14"
// Check if all satisfy a predicate
template <typename... Args>
bool all_positive(Args... args) {
return (... && (args > 0)); // Left fold
}

Four forms of fold expressions:

SyntaxNameExpansion
(pack op ...)Unary right folda1 op (a2 op (a3 op ...))
(... op pack)Unary left fold((a1 op a2) op a3) op ...
(pack op ... op init)Binary right folda1 op (a2 op (... op init))
(init op ... op pack)Binary left fold((init op a1) op a2) op ...

Concepts (C++20)

Concepts let you constrain template parameters with requirements you can actually read aloud:

cpp
#include <concepts>
#include <iostream>
// Define a concept
template <typename T>
concept Numeric = std::is_arithmetic_v<T>;
template <typename T>
concept Printable = requires(T t) {
{ std::cout << t } -> std::same_as<std::ostream&>;
};
template <typename T>
concept Sortable = requires(T a, T b) {
{ a < b } -> std::convertible_to<bool>;
{ a == b } -> std::convertible_to<bool>;
};
// Use concepts to constrain templates
template <Numeric T>
T add(T a, T b) {
return a + b;
}
// Or with requires clause
template <typename T>
requires Sortable<T> && Printable<T>
void sort_and_print(std::vector<T>& v) {
std::sort(v.begin(), v.end());
for (const auto& elem : v) {
std::cout << elem << " ";
}
std::cout << "\n";
}

Concepts replace SFINAE — Substitution Failure Is Not An Error, the compiler trick template authors lived on for a decade — with constraints you can read without going cross-eyed:

cpp
// Old SFINAE approach (hard to read)
template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
T old_add(T a, T b) { return a + b; }
// New concept approach (clear and readable)
template <Numeric T>
T new_add(T a, T b) { return a + b; }

Compile-Time String Processing

cpp
constexpr bool starts_with(std::string_view str, std::string_view prefix) {
if (prefix.size() > str.size()) return false;
for (size_t i = 0; i < prefix.size(); i++) {
if (str[i] != prefix[i]) return false;
}
return true;
}
static_assert(starts_with("hello world", "hello"));
static_assert(!starts_with("hello world", "world"));

consteval: Always Compile-Time

If constexpr is a request, consteval (C++20) is a demand — the function must run at compile time or fail to compile:

cpp
consteval int compile_time_only(int n) {
return n * n;
}
constexpr int a = compile_time_only(5); // OK: 25 at compile time
int runtime_val = 5;
// int b = compile_time_only(runtime_val); // ERROR: not compile-time

Practical Example: A Stream-Based Printf

cpp
#include <iostream>
#include <string_view>
template <typename T>
concept Formattable = requires(std::ostream& os, T t) {
{ os << t };
};
template <Formattable... Args>
void safe_printf(std::string_view fmt, Args&&... args) {
auto arg_tuple = std::make_tuple(std::forward<Args>(args)...);
size_t arg_idx = 0;
for (size_t i = 0; i < fmt.size(); i++) {
if (fmt[i] == '{' && i + 1 < fmt.size() && fmt[i + 1] == '}') {
// Print next argument using fold expression trick
std::apply([&](auto&&... a) {
size_t idx = 0;
((idx++ == arg_idx ? (std::cout << a, true) : false) || ...);
}, arg_tuple);
arg_idx++;
i++; // Skip '}'
} else {
std::cout << fmt[i];
}
}
}

This is safer than C's printf, because every argument goes through operator<< instead of being pulled off a varargs list by a format letter, and the Formattable concept rejects unprintable types at compile time. The format string itself goes unchecked, though. safe_printf("{} and {}", 1) compiles and prints 1 and with the second slot silently empty, and surplus arguments vanish without a word.

For real code, use the standard library. C++20's std::format checks the format string against the argument types at compile time (that check arrived through P2216, which was applied to C++20 retroactively), and C++23 adds std::print on the same machinery:

cpp
#include <format>
#include <iostream>
std::cout << std::format("{} is {}\n", "answer", 42); // answer is 42
// std::format("{} and {}\n", 1); // compile error: no argument for the second {}

When to Use Metaprogramming

Use compile-time computation when:

  • Performance matters: Move work from runtime to compile time
  • Type safety matters: Catch errors before the program runs
  • Code generation: Generate specialised code for each type
  • Configuration: Compile-time feature flags and conditional compilation

Avoid metaprogramming when:

  • Simple runtime code would be clearer
  • Compile times are already slow
  • The types are not known until runtime