From fb3faefd2e01bd6060c04debb9b1e8b54769d37e Mon Sep 17 00:00:00 2001 From: Alexis Dumas Date: Fri, 21 Aug 2026 09:03:02 -0400 Subject: [PATCH] Chapter 19: NTTPs and UDLs --- book/src/ch19-nttps-and-udls.md | 123 ++++++++++++++++++++++++++++++ examples/CMakeLists.txt | 1 + examples/ch19/CMakeLists.txt | 19 +++++ examples/ch19/fixed_string.cpp | 31 ++++++++ examples/ch19/nttp_basic.cpp | 15 ++++ examples/ch19/structural_nttp.cpp | 26 +++++++ examples/ch19/udl_distance.cpp | 17 +++++ examples/ch19/udl_parse.cpp | 26 +++++++ examples/ch19/units_ratio.cpp | 18 +++++ 9 files changed, 276 insertions(+) create mode 100644 book/src/ch19-nttps-and-udls.md create mode 100644 examples/ch19/CMakeLists.txt create mode 100644 examples/ch19/fixed_string.cpp create mode 100644 examples/ch19/nttp_basic.cpp create mode 100644 examples/ch19/structural_nttp.cpp create mode 100644 examples/ch19/udl_distance.cpp create mode 100644 examples/ch19/udl_parse.cpp create mode 100644 examples/ch19/units_ratio.cpp diff --git a/book/src/ch19-nttps-and-udls.md b/book/src/ch19-nttps-and-udls.md new file mode 100644 index 0000000..0a74231 --- /dev/null +++ b/book/src/ch19-nttps-and-udls.md @@ -0,0 +1,123 @@ +# 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` 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`, deduces the type of the argument automatically. 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 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. + +```cpp +{{#include ../../examples/ch19/nttp_basic.cpp}} +``` + + +NTTPs enable compile‑time decisions that otherwise require runtime branches. For example a function template can select an optimized algorithm when the size argument is a power of two. The compiler evaluates the condition during translation and instantiates only the matching overload. + +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, providing a zero‑overhead dispatch table for command strings. + +* 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, allowing `template` to accept any of the above categories. + +The type of an NTTP determines what can appear as the argument. Integral and enumeration constants are the most common. Pointers and references to objects with static storage duration are allowed. Since C++20 a structural class type can appear as a value. The `auto` NTTP form deduces whichever category the argument belongs to, which is why `template` accepts all of them uniformly. + +--- + +## 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. + +```cpp +{{#include ../../examples/ch19/structural_nttp.cpp}} +``` + +`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_assert`s verify the values during translation, while the program prints a short marker confirming successful runtime execution. + +Structural NTTPs enable patterns such as compile‑time configuration tables, policy objects that influence algorithm selection, and domain‑specific languages that pass complete objects as arguments without any runtime overhead. + +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. + +```cpp +{{#include ../../examples/ch19/fixed_string.cpp}} +``` + +`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` 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. + +--- + +## 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. + +```cpp +{{#include ../../examples/ch19/udl_distance.cpp}} +``` + +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, turning 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. + +```cpp +{{#include ../../examples/ch19/udl_parse.cpp}} +``` + +`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, PROSE) + +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` 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. + +```cpp +{{#include ../../examples/ch19/units_ratio.cpp}} +``` + +`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`. diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 9dc8690..a9208e8 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -16,3 +16,4 @@ add_subdirectory(ch15) add_subdirectory(ch16) add_subdirectory(ch17) add_subdirectory(ch18) +add_subdirectory(ch19) diff --git a/examples/ch19/CMakeLists.txt b/examples/ch19/CMakeLists.txt new file mode 100644 index 0000000..408e319 --- /dev/null +++ b/examples/ch19/CMakeLists.txt @@ -0,0 +1,19 @@ +# Register NTTP and UDL examples for Chapter 19 + +# Basic NTTP example +book_example(${CMAKE_CURRENT_SOURCE_DIR}/nttp_basic.cpp EXPECT "Arr size:") + +# Structural NTTP example +book_example(${CMAKE_CURRENT_SOURCE_DIR}/structural_nttp.cpp EXPECT "config a=3") + +# Fixed‑string NTTP example +book_example(${CMAKE_CURRENT_SOURCE_DIR}/fixed_string.cpp EXPECT "fixed_string: hello") + +# User‑defined literal for distance +book_example(${CMAKE_CURRENT_SOURCE_DIR}/udl_distance.cpp EXPECT "Distance: 5 km") + +# Consteval parsing UDL +book_example(${CMAKE_CURRENT_SOURCE_DIR}/udl_parse.cpp EXPECT "Parsed number: 1234") + +# Units example using std::ratio +book_example(${CMAKE_CURRENT_SOURCE_DIR}/units_ratio.cpp EXPECT "speed = 10 m/s") diff --git a/examples/ch19/fixed_string.cpp b/examples/ch19/fixed_string.cpp new file mode 100644 index 0000000..c948440 --- /dev/null +++ b/examples/ch19/fixed_string.cpp @@ -0,0 +1,31 @@ +#include +#include + +// Fixed‑string non‑type template parameter. +// Stores the characters of a literal at compile time. + +template +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 +fixed_string(const char(&)[N]) -> fixed_string; + +// Example function taking a fixed_string NTTP. +template +void print_fixed() { + std::cout << "fixed_string: " << S.buf << " (size=" << S.size() << ")" << std::endl; +} + +int main() { + print_fixed<"hello">(); + return 0; +} diff --git a/examples/ch19/nttp_basic.cpp b/examples/ch19/nttp_basic.cpp new file mode 100644 index 0000000..99ec16f --- /dev/null +++ b/examples/ch19/nttp_basic.cpp @@ -0,0 +1,15 @@ +#include + +// Basic non‑type template parameter: size of an array. +// The size N is a compile‑time constant supplied as a template argument. + +template +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; +} diff --git a/examples/ch19/structural_nttp.cpp b/examples/ch19/structural_nttp.cpp new file mode 100644 index 0000000..0d34347 --- /dev/null +++ b/examples/ch19/structural_nttp.cpp @@ -0,0 +1,26 @@ +#include + +// 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 +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; + 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; +} diff --git a/examples/ch19/udl_distance.cpp b/examples/ch19/udl_distance.cpp new file mode 100644 index 0000000..fa91797 --- /dev/null +++ b/examples/ch19/udl_distance.cpp @@ -0,0 +1,17 @@ +#include + +struct Distance { + double value; + const char* unit; +}; + +// User‑defined literal for kilometres. +constexpr Distance operator""_km(long double v) { + return Distance{static_cast(v), "km"}; +} + +int main() { + constexpr Distance d = 5.0_km; + std::cout << "Distance: " << d.value << " " << d.unit << std::endl; + return 0; +} diff --git a/examples/ch19/udl_parse.cpp b/examples/ch19/udl_parse.cpp new file mode 100644 index 0000000..e9a1c2a --- /dev/null +++ b/examples/ch19/udl_parse.cpp @@ -0,0 +1,26 @@ +#include +#include + +// 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(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; +} diff --git a/examples/ch19/units_ratio.cpp b/examples/ch19/units_ratio.cpp new file mode 100644 index 0000000..5eca0d1 --- /dev/null +++ b/examples/ch19/units_ratio.cpp @@ -0,0 +1,18 @@ +#include +#include + +// Compile‑time ratio representing a speed unit (length / time). + +template +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; +} -- 2.51.2