Template Metaprogramming

Template Metaprogramming in C++

Learn how C++ template metaprogramming runs code at compile time, with examples of recursive templates, type traits, if constexpr and concepts.

On this page
  1. What metaprogramming means
  2. A first example: a factorial computed by the compiler
  3. Constant expressions with constexpr
  4. Checking types with type traits
  5. Choosing overloads with enable_if
  6. Branching at compile time with if constexpr
  7. Constraining templates with concepts
  8. Variadic templates and fold expressions
  9. When to use it, and when not to
  10. Where to go next

If you searched for c metaprogramming, the short answer is that C++ does it with templates. Metaprogramming is code that works on other code. In C++, a template is a pattern that the compiler fills in for the types and values it needs, and the compiler can run that work during the build. The program that finally runs often contains only the result.

This guide is for readers who already know basic function and class templates. The techniques are grouped roughly in the order C++ added them, from older recursive templates to newer features such as concepts.

What metaprogramming means

Metaprogramming is writing code whose job is to produce or check other code. In C++, the “other code” is usually types or constant values. When the inputs are known at compile time, the compiler can evaluate them then, and it reports a build error if an assumption fails.

Templates are the main tool for this. They are not only for generic containers such as std::vector. They can also make decisions, such as choosing one type over another or computing a number, before the program starts.

A first example: a factorial computed by the compiler

A class template can take a number as a template parameter and refer to a smaller instance of itself. A full specialization for 0 ends the recursion.

template <unsigned int N>
struct Factorial {
    static constexpr unsigned long long value = N * Factorial<N - 1>::value;
};

template <>
struct Factorial<0> {
    static constexpr unsigned long long value = 1;
};

static_assert(Factorial<5>::value == 120, "5! is 120");

static_assert is checked during compilation. If the value were wrong, the build would stop with the message you wrote. Because value is a constant expression, the compiler knows its result before the program runs.

Before C++11, recursive templates were one of the few ways to compute values at compile time. The style still appears in older code, but it is hard to read, so newer code usually uses the next approach.

Constant expressions with constexpr

C++11 added constexpr, which lets an ordinary function run at compile time when its arguments are known at compile time. C++14 relaxed the rules so that a constexpr function can use loops.

constexpr unsigned long long factorial(unsigned int n) {
    unsigned long long result = 1;
    for (unsigned int i = 2; i <= n; ++i) {
        result *= i;
    }
    return result;
}

static_assert(factorial(5) == 120, "5! is 120");

This version reads like normal C++. The same function can also be called at run time with a value that is only known then, so you do not need a separate version for compile-time use.

Checking types with type traits

The header <type_traits> provides templates that answer questions about types. Each one has a value member that is true or false. In C++17 there is also a shorter _v form, such as std::is_same_v<int, int>.

#include <type_traits>

static_assert(std::is_same<int, int>::value, "the types match");
static_assert(!std::is_same<int, long>::value, "the types differ");

std::is_same checks whether two types are identical. Other traits check broader properties, such as whether a type is an integer type. Libraries use these checks to reject unsupported types at compile time.

Choosing overloads with enable_if

std::enable_if is a template that only has a usable member when a condition is true. When substituting an argument into a function signature fails, the compiler drops that overload rather than stopping. This rule is often called SFINAE, which stands for “substitution failure is not an error.”

#include <type_traits>

template <typename T>
typename std::enable_if<std::is_integral<T>::value, T>::type
twice(T value) {
    return value * 2;
}

Calling twice(4) returns 8. Calling twice(2.5) finds no matching function and fails to compile. The signature is harder to read than the later examples, which is one reason newer C++ prefers concepts.

Branching at compile time with if constexpr

C++17 added if constexpr. When its condition is known at compile time, the branch that is not taken is discarded. That branch does not have to be valid for the type in use.

#include <iostream>
#include <type_traits>

template <typename T>
void show(T value) {
    if constexpr (std::is_integral_v<T>) {
        std::cout << "whole number: " << value << '\n';
    } else {
        std::cout << "not a whole number: " << value << '\n';
    }
}

Both show(3) and show(2.5) compile. Before C++17, the same branching usually needed a separate enable_if overload for each case.

Constraining templates with concepts

C++20 added concepts, which name the requirements a template argument must meet. A function can state its requirement right in the template header.

#include <concepts>

template <std::integral T>
T twice(T value) {
    return value * 2;
}

This does the same job as the enable_if version above, in fewer lines. When a call breaks the requirement, the compiler error usually names the concept, which can be easier to read than an overload failure.

Variadic templates and fold expressions

Since C++11, a template can take any number of arguments through a parameter pack, written typename... Args. C++17 fold expressions apply an operator across the pack.

template <typename... Args>
auto sum(Args... args) {
    return (args + ...);
}

sum(1, 2, 3) returns 6. The fold needs at least one argument. The standard library’s std::tuple is a well-known use of this idea, and the basics are in tuple in c.

When to use it, and when not to

Template metaprogramming can move checks earlier, avoid run-time work, and let one function serve many types. It also has costs:

  • Heavy template use can make builds slower.
  • Errors from failed templates can run to many lines of compiler output.
  • Code that uses these techniques can be hard to read for people new to them.

Many problems do not need compile-time code. A plain function or a run-time design often works better. Run-time polymorphism, which uses virtual functions, solves some of the same design problems in a different way, covered in polymorphism in c.

Older C code often used macros for compile-time work. Macros have pitfalls that templates avoid, and the trade-offs are covered in why not use macros in C++.

Where to go next

Learn function templates and class templates first. Then read about static_assert and type traits, which show up throughout library code. After that, if constexpr and concepts cover most modern cases.

Templates are usually defined in header files, and a header that is included in many places needs a header guard in c or #pragma once. Without one, the same template definition can appear twice in one file and cause an error. Alias templates are declared with using, a common next step covered in c using keyword.

Keep exploring

Guides from other topics

All topics →

The final Keyword in C++

Learn how the final keyword in C++ stops a class from being inherited or a virtual function from being overridden, with short, working code examples.

final 4 min read