Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Values as template arguments and user-defined literals

Non‑type template parameters (NTTPs)

Non‑type template parameters turn compile‑time values into part of the type system. By embedding a constant in a template argument the compiler generates a distinct specialization for each value. This enables zero‑overhead dispatch: the generated code contains only the paths required for the specific constant, and any branches that depend on the value disappear after constant folding. Standard library containers such as std::array<T,N> and std::span rely on this technique to expose size information without runtime storage. Compile‑time bounds checking, static‑asserted preconditions, and compile‑time hash tables also become possible when the size or key is an NTTP.

The auto NTTP form, template<auto V>, deduces the argument type. It accepts an integral, pointer, reference, or structural class object. This pattern forwards a value without naming its type, reducing boilerplate. The compiler encodes the value in the mangled name, giving each distinct argument a unique symbol. Using many distinct values can increase binary size, but the gain is eliminating runtime conditionals. It accepts an integral, a pointer, a reference, or a structural class object. Generic utilities frequently use this pattern to forward a value to another template without naming its type, reducing boilerplate and improving readability. The compiler records the value in the mangled name of the instantiation, so each distinct argument yields a unique symbol. This can increase binary size if many values are used, but the trade‑off is often worthwhile for the performance gain of eliminating runtime conditionals.

When an NTTP participates in overload resolution, the compiler prefers a more specialized non‑type argument. This mirrors concept overload resolution and enables tag‑dispatch based on constexpr values. For example, a function template can provide a fast path for a power‑of‑two size by matching template<std::size_t N> requires (N & (N-1)) == 0.

C++26 extends NTTPs to floating‑point values and to class types with non‑trivial constructors, simplifying patterns that rely on encoding a floating value in an integral representation.

Before C++26, a floating‑point NTTP required a workaround: encode the value as a fraction of two integers, or store it in a constexpr static variable and pass a reference. The extension makes the value a direct template argument, so a template can specialise on a literal 1.5 the same way it specialises on an integer. The class-type extension lifts the structural-type restriction that required aggregate initialisation, so a type with a constexpr constructor can now appear as an NTTP even if it has a non-trivial one.

#include <iostream>

// Basic non‑type template parameter: size of an array.
// The size N is a compile‑time constant supplied as a template argument.

template<int N>
struct Arr {
    int data[N]{}; // array of N ints, default‑initialized to zero
};

int main() {
    Arr<5> a; // N = 5
    std::cout << "Arr size: " << sizeof(a) << " bytes" << std::endl;
    return 0;
}

Compile‑time hashing of string literals also relies on NTTPs. A hash function defined as constexpr can accept a fixed_string NTTP and produce a constant hash value. This value can be used as a case label in a switch statement. The result is a zero‑overhead dispatch table for command strings.

An NTTP argument must come from one of a fixed set of categories:

  • Integral and enumeration constants (int, char, enum).
  • Pointers or references to objects with static storage duration, including function pointers.
  • Class‑type values that satisfy the structural type requirements.
  • auto can deduce the type. This allows template<auto V> to accept any of the above categories.

Class‑type NTTPs (C++20)

C++20 extends NTTPs to accept structural types. A structural type is a class or struct whose members are all public, have non‑mutable types, and themselves are structural. The class must not declare any user‑provided constructor, so it can be aggregate‑initialized.

#include <iostream>

// Structural non‑type template parameter.
// The type must be a structural type: all members are public, no mutable, no user‑declared constructor.

struct Config {
    int a;
    double b;
};

// The template takes a Config as a compile‑time value.

template<Config C>
struct UseConfig {
    static constexpr int val_a = C.a;
    static constexpr double val_b = C.b;
};

int main() {
    // Instantiate with a concrete Config value.
    using My = UseConfig<Config{3, 4.5}>;
    static_assert(My::val_a == 3);
    static_assert(My::val_b == 4.5);
    std::cout << "config a=" << My::val_a << " b=" << My::val_b << std::endl;
    return 0;
}

Config satisfies the structural rules: it contains two data members, both of which are fundamental types, and the struct has no constructors. The template UseConfig receives a concrete Config{3,4.5} as a compile‑time constant. Inside the specialization the values appear as constexpr static data members. The static_asserts verify the values during translation, while the program prints a short marker confirming successful runtime execution.

Structural NTTPs enable compile‑time configuration tables, policy objects, and domain‑specific languages without runtime overhead. The structural‑type rule requires all members to be public and non‑mutable, so the compiler can compare two NTTPs for equality during overload resolution and template deduplication. Two aggregates are equal when their members are equal, which keeps hashing and name mangling well defined.

The structural-type rule exists so the compiler can compare two NTTPs for equality during overload resolution and template deduplication. Because every member is public and the class has no user constructor, two aggregate values are equal exactly when their members are equal, which keeps hashing and name mangling well defined. This is what lets a Config{3, 4.5} name one unique specialization.

The fixed_string recipe

Passing a literal string as an NTTP is a common requirement, but the language does not provide a built‑in string NTTP. A small helper class called fixed_string fills this gap. It stores the characters of a literal in a constexpr array and supplies a deduction guide so that a plain string literal can be used directly as a template argument.

#include <iostream>
#include <cstddef>

// Fixed‑string non‑type template parameter.
// Stores the characters of a literal at compile time.

template<std::size_t N>
struct fixed_string {
    char buf[N]{};
    // constexpr constructor copies characters.
    constexpr fixed_string(const char(&s)[N]) {
        for (std::size_t i = 0; i < N; ++i) buf[i] = s[i];
    }
    // constexpr size query.
    constexpr std::size_t size() const { return N; }
};

// Deduction guide from a string literal.
template<std::size_t N>
fixed_string(const char(&)[N]) -> fixed_string<N>;

// Example function taking a fixed_string NTTP.
template<fixed_string S>
void print_fixed() {
    std::cout << "fixed_string: " << S.buf << " (size=" << S.size() << ")" << std::endl;
}

int main() {
    print_fixed<"hello">();
    return 0;
}

fixed_string is a class template parameterised by the literal length N. Its constexpr constructor copies each character from the literal into the internal buffer buf. The deduction guide fixed_string(const char(&)[N]) -> fixed_string<N> allows the user to write print_fixed<"hello">() without explicitly naming the size.

The function print_fixed receives the fixed_string as an NTTP and can access the characters at compile time. The size() member reports the length, and the runtime std::cout prints the stored characters. This technique underlies many compile‑time parsers, compile‑time reflection utilities, and the constexpr‑SQL capstone in Chapter 22.

Because the characters live in the buffer, a consteval parser can walk S.buf at compile time to validate or transform the literal before any runtime code exists. This is the foundation of the compile-time parsing that chapter 22 exploits for its SQL engine: the query string is checked, tokenized, and turned into row types while the program is still being translated.

The structural-type rule is what makes fixed_string legal as an NTTP. Every member is public, the class has no user-declared constructors beyond the constexpr one, and the array of char is a structural type. Two fixed_string values with the same characters produce the same template argument, so the compiler can deduplicate the specialization. This is the same rule that lets a Config{3, 4.5} name one unique specialization, applied to text instead of numbers.

User‑defined literals (UDLs)

A user‑defined literal extends the set of literal suffixes that the language recognises. The compiler looks for a function named operator""_suffix in the same namespace as the call site (or via argument‑dependent lookup). The function can accept an integral, floating‑point, character, or string literal form.

#include <iostream>

struct Distance {
    double value;
    const char* unit;
};

// User‑defined literal for kilometres.
constexpr Distance operator""_km(long double v) {
    return Distance{static_cast<double>(v), "km"};
}

int main() {
    constexpr Distance d = 5.0_km;
    std::cout << "Distance: " << d.value << " " << d.unit << std::endl;
    return 0;
}

The example defines a literal suffix _km that converts a floating‑point literal into a Distance object. The operator""_km is constexpr, so the expression 5.0_km is computed at compile time. The program prints Distance: 5 km, which the test harness verifies with the regular expression Distance: 5 km.

User‑defined literals give a natural, readable syntax for domain‑specific units, bit masks, or compile‑time identifiers. Because they are ordinary functions they can be overloaded, templated, and placed in header files for reuse across translation units.

A UDL has a form for each literal category. Integer literals dispatch to operator""_suffix(unsigned long long), floating-point literals to operator""_suffix(long double), character literals to operator""_suffix(char), and string literals to operator""_suffix(const char*, std::size_t). The _suffix identifier must begin with an underscore. A suffix without a leading underscore is reserved for the implementation. Placing the operator in a namespace and bringing it in with using keeps the literal vocabulary explicit.

UDLs for parsed literals (constexpr)

A more advanced use of UDLs parses the literal characters at compile time. It turns a string literal into a value without any runtime work. The function must be consteval (or constexpr in C++20) and can perform arbitrary compile‑time computation.

#include <iostream>
#include <cstddef>

// consteval user‑defined literal that parses a decimal integer from a string.
// The literal receives the characters and length of the literal.

consteval unsigned int parse_number(const char* str, std::size_t len) {
    unsigned int value = 0;
    for (std::size_t i = 0; i < len; ++i) {
        char c = str[i];
        value = value * 10 + static_cast<unsigned int>(c - '0');
    }
    return value;
}

// UDL suffix _num parses a literal string like "1234"_num into an unsigned int.
consteval unsigned int operator""_num(const char* str, std::size_t len) {
    return parse_number(str, len);
}

int main() {
    constexpr unsigned int v = "1234"_num;
    static_assert(v == 1234);
    std::cout << "Parsed number: " << v << std::endl;
    return 0;
}

operator""_num receives the raw character data and length of the literal. It iterates over the characters, computes the numeric value, and returns it. The parse runs entirely during translation because the literal is a compile-time constant, and the compiler folds the result into the constant v.

In main the literal "1234"_num is parsed into the constant v. A static_assert verifies the result, and the program prints Parsed number: 1234. This pattern is useful for compile‑time parsing of IP addresses, colour codes, or UUID strings.

NTTP callables (C++26)

C++26 adds the ability to pass a callable (a function pointer, lambda, or function object) as a non‑type template argument. The placeholder syntax template<auto F> captures the callable, and the template can invoke it at compile time. The standard library also introduces std::bind_front and std::bind_back, which adapt a callable by pre‑binding or post‑binding arguments, and the resulting binder can be used as an NTTP.

Not yet deployable. NTTP callables and std::bind_front/bind_back are part of the C++26 draft. Current Clang versions lack support, so no compiled example is provided. Readers can experiment with GCC 16 or later once the feature lands.

Units example (NTTP ratios)

Compile‑time unit arithmetic can be expressed using std::ratio, a compile‑time fraction type introduced in Chapter 15. By making a ratio an NTTP a template can encode a conversion factor that the compiler evaluates without runtime cost.

#include <iostream>
#include <ratio>

// Compile‑time ratio representing a speed unit (length / time).

template<int Num, int Den>
struct SpeedRatio {
    static constexpr int num = Num;
    static constexpr int den = Den;
    static void print() {
        std::cout << "speed = " << num << " m/s" << std::endl;
    }
};

int main() {
    SpeedRatio<10,1>::print(); // 10 metres per second
    return 0;
}

SpeedRatio stores a numerator and denominator as template arguments. The print member writes a human‑readable representation. The values are known at compile time, so any arithmetic involving the ratio is folded by the optimizer. The program prints speed = 10 m/s, matching the test harness expectation.

Because the conversion factors are ratios baked into the type, a m/s result and a km/h result cannot be mixed silently. The compiler rejects arithmetic that requires an unknown conversion and accepts only what a dimension analysis allows. This turns a class of unit errors into compile-time diagnostics, the same payoff as the lifetime analysis of chapter 07 but for dimensional correctness. Each std::ratio pair is a distinct type, so meter and second are unrelated unless a template combines them into meter_per_second.

Advanced NTTP patterns

Beyond basic usage, NTTPs can drive compile‑time state machines, generate lookup tables, and enable perfect‑hash dispatch. By encoding a map of string keys to function pointers as a constexpr array of fixed_string/function pointer pairs, a switch on the NTTP can select the handler at compile time, eliminating any runtime map lookup. This approach is useful for command‑line parsers, protocol dispatch, or embedded DSLs where the set of commands is fixed.

The cost is that each distinct NTTP emits a separate specialization, so a table of one hundred string keys produces one hundred instantiations. The technique pays off when the set of commands is fixed and dispatch is hot. For a set that changes, a runtime std::map is simpler. Perfect hashing over fixed_string keys turns a linear scan of command names into a single arithmetic jump, so a hot dispatch loop stays branch-predictable and never performs a runtime string comparison.

Try this

Write a user‑defined literal _hex that parses a hexadecimal string literal into an unsigned integer at compile time and verify the result with a static_assert.