Cheat Sheet - Linux: /linux/ - CLI: /linux/cli/ - locate vs type vs which vs whereis: /linux/cli/locate-vs-type-vs-which-vs-whereis/ - make: /linux/cli/make/ - awk: /linux/cli/awk/ - find: /linux/cli/find/ - grep: /linux/cli/grep/ - pgrep: /linux/cli/pgrep/ - ps: /linux/cli/ps/ - pstree: /linux/cli/pstree/ - trap: /linux/cli/trap/ - xargs: /linux/cli/xargs/ - Shell: /linux/shell/ - BASH_SOURCE: /linux/shell/bash-source/ - Redirection: /linux/shell/redirection/ - Special Variables: /linux/shell/special-variables/ - Scripting Tips: /linux/shell/script-tips/ - set -o vi: /linux/shell/bash-vi-mode/ - Shell Processing Order: /linux/shell/process-order/ - What are Interactive and Login Shells?: /linux/shell/interactive-login/ - Double Quote Expansion: /linux/shell/shell-expansion/ - System Programming: /linux/system-programming/ - File I/O: /linux/system-programming/file-io/ - Process: /linux/system-programming/process/ - Shared Libraries: /linux/system-programming/shared-libraries/ - Kernel: /linux/kernel/ - Go: /programming/go/ - Concurrency: /programming/go/concurrency/ - CSP (Communicating Sequential Processes) and Channels: /programming/go/concurrency/csp/ - Channel: /programming/go/concurrency/channel/ - Select: /programming/go/concurrency/select/ - sync: /programming/go/concurrency/sync/ - Concurrency Patterns: /programming/go/concurrency/patterns/ - Goroutines and the Go Runtime: /programming/go/concurrency/runtime/ - Standard Library: /programming/go/std/ - os: /programming/go/std/os/ - context: /programming/go/std/context/ - io: /programming/go/std/io/ - json: /programming/go/std/json/ - net/http: /programming/go/std/net-http/ - slog: /programming/go/std/slog/ - testing: /programming/go/std/testing/ - time: /programming/go/std/time/ - Ellipsis (...): /programming/go/ellipsis/ - error: /programming/go/error/ - Function: /programming/go/function/ - Go Tool: /programming/go/tool/ - Interface: /programming/go/interface/ - Map: /programming/go/map/ - Package and Module: /programming/go/package-module/ - Pointer: /programming/go/pointer/ - Slice: /programming/go/slice/ - String: /programming/go/string/ - Switch: /programming/go/switch/ - Comparison: /programming/go/comparison/ - defaultdict: /programming/python/collections/defaultdict/ - heapq: /programming/python/collections/heapq/ - @cache: /programming/python/cache/ - abc: /programming/python/abc/ - bisect: /programming/python/bisect/ - Type Hints: /programming/python/type-hints/ - Passing Mechanism: /programming/python/passing-mechanism/ - uv: /programming/python/uv/ - *args and **kwargs: /programming/python/args-kwargs/ - re: /programming/python/re/ - C: /programming/c/ - Pointers and Arrays: /programming/c/pointer/ - Syntax Basics: /programming/c/syntax-basics/ - static: /programming/c/static/ - Bit Manipulation: /programming/c/bit-manipulation/ - C vs C++: /programming/c/c-vs-cpp/ - stdatomic: /programming/c/stdatomic/ - C++: /programming/cpp/ - RAII (Resource Acquisition Is Initialization): /programming/cpp/raii/ - Copy Elision & Move Semantics: /programming/cpp/copy-elision-and-move-semantics/ - Most Vexing Parse & In-Class Initializer: /programming/cpp/most-vexing-parse/ - C++ Keywords Reference: /programming/cpp/keywords/ - C++ Primer: /programming/cpp/primer/ - Variables and Basic Types: /programming/cpp/primer/variables-and-basic-types/ - Expressions: /programming/cpp/primer/expressions/ - Type Conversions and Casts: /programming/cpp/primer/type-conversions-and-casts/ - Statements: /programming/cpp/primer/statements/ - Functions: /programming/cpp/primer/functions/ - Classes: /programming/cpp/primer/classes/ - The IO Library: /programming/cpp/primer/io-library/ - STL: /programming/cpp/primer/stl/ - Lambda Expressions: /programming/cpp/primer/lambda/ - Smart Pointers: /programming/cpp/primer/smart-pointers/ - Copy Control: /programming/cpp/primer/copy-control/ - Overloaded Operations and Conversions: /programming/cpp/primer/operator-overloading/ - Object-Oriented Programming (OOP): /programming/cpp/primer/oop/ - Templates and Generic Programming: /programming/cpp/primer/templates/ - Namespaces: /programming/cpp/primer/namespaces/ - Pointers to Class Member: /programming/cpp/primer/pointers-to-class-member/ - Advanced: /programming/cpp/advanced/ - Error Handling: /programming/cpp/advanced/error-handling/ - Concurrency & Threading: /programming/cpp/advanced/concurrency/ - Unit Testing: /programming/cpp/advanced/unit-testing/ - Comparison: /programming/comparison/ - Kubernetes: /cloud-devops/kubernetes/ - Fleet: /cloud-devops/kubernetes/gke/fleet/ - Kustomize vs Helm: /cloud-devops/kubernetes/kustomize-vs-helm/ - API Extension: /cloud-devops/kubernetes/api-extension/ - Concept: /cloud-devops/kubernetes/kueue/concept/ - DRA: /cloud-devops/kubernetes/dra/ - Secret Manager: /cloud-devops/terraform/google-secret-manager/ - Knowledge: /network/knowledge/ - PDU: /network/knowledge/osi-model/ - curl: /network/cli/curl/ - Concurrency Concepts: /cs/concurrency-and-parallelism/concepts/ - Concurrency vs Parallelism: /cs/concurrency-and-parallelism/concurrency-vs-parallelism/ - Mutex vs Atomic: /cs/concurrency-and-parallelism/mutex-vs-atomic/ - Regular Expression: /cs/regular-expression/ - Multiplexer vs Dispatcher: /cs/multiplexer-vs-dispatcher/ - Driver and Runtime: /ai-ml/gpu/driver-and-runtime/ - Serving: /ai-ml/serving/ - Dotfiles: /dotfiles/ - Git: /dotfiles/git/ - Cheat Sheet: /dotfiles/git/cheat-sheet/ - revisions: /dotfiles/git/revisions/ - Submodule vs Worktree: /dotfiles/git/submodule-vs-worktree/ - checkout, reset -> switch, restore: /dotfiles/git/checkout-switch-restore-reset/ - rebase: /dotfiles/git/rebase/ - Branching and Merging: /dotfiles/git/branching-merging/ - Vim: /dotfiles/vim/ - Plugin: /dotfiles/vim/plugin/ - auto-pairs: /dotfiles/vim/plugin/auto-pairs/ - vim-commentary: /dotfiles/vim/plugin/vim-commentary/ - vim-easymotion: /dotfiles/vim/plugin/vim-easymotion/ - vim-surround: /dotfiles/vim/plugin/vim-surround/ - Marks: /dotfiles/vim/tips/marks/ - vimrc: /dotfiles/vim/vimrc/ - lf: /dotfiles/lf/ # Templates and Generic Programming {{< katex />}} Based on *C++ Primer, 5th ed.*, Chapter 16 (Templates and Generic Programming), this post summarizes function and class template instantiation, template argument deduction, **forwarding references (`T&&`) and reference collapsing**, **variadic templates (`Args...`) and how `emplace_back` works under the hood**, and template specialization. ## 1. Function and Class Template Fundamentals - **Template Instantiation:** A template itself is a **blueprint**, not executable code. When you invoke `compare(1, 0)` or declare `std::vector`, the compiler substitutes the concrete type for `T` and instantiates a type-specific version of the function or class. - **Why Must Template Declarations and Definitions Live in Header Files (`.h`)?** - For an ordinary function, the compiler only needs the declaration to compile a call site, and the linker later links the `.o` object file. **To instantiate a template, however, the compiler must see the full template body at the call site** so it can generate code for the concrete type. ### 1. Type Parameters (`typename` / `class`) and Non-type Template Parameters In addition to type parameters (`typename T`), templates can take **non-type template parameters** representing compile-time constant expressions (`constexpr` integers, pointers, or references): ```cpp // 1. Type template parameter (typename and class are 100% interchangeable here) template int compare(const T &v1, const T &v2) { if (v1 < v2) return -1; if (v2 < v1) return 1; return 0; } // 2. Non-type Template Parameters (unsigned N, unsigned M): // Binds references to arrays directly without pointer decay template int compare(const char (&p1)[N], const char (&p2)[M]) { return strcmp(p1, p2); } int r = compare("hi", "mom"); // At the call site, compiler deduces N as 3 and M as 4, instantiating compare<3, 4> ``` ### 2. Dependent Type Names and the Mandatory `typename` Rule When accessing a name nested inside a template type parameter such as `T::Bar`, the compiler does not know before instantiation whether that name refers to a **nested type** or a **non-type member** such as a `static` data member, `static` member function, or enumerator. For example, the grammatical meaning of `T::Bar * x;` changes completely depending on `T`: ```cpp int x = 10; template void func() { T::Bar * x; // Pointer variable declaration, or multiplication expression? } ``` - If `struct A { using Bar = int; };` is passed (`Bar` is a nested type): it means `int * x;`, a **pointer variable declaration** (`*` is the pointer declarator). - If `struct B { static int Bar; };` is passed (`Bar` is a `static` variable): it multiplies `B::Bar` and `x` as a **multiplication expression** (`*` is the multiplication operator). To resolve this ambiguity, C++ **assumes by default that an unadorned `T::...` is not a type**. To tell the compiler that `T::...` names a **type**, you must prefix it with **`typename`**; `class` cannot be used here: ```cpp template // 'typename' is required to inform the compiler that these dependent names are types typename Container::value_type top_element(const Container &c) { typename Container::const_iterator it = c.begin(); return *it; } ``` --- ## 2. Template Argument Deduction & Reference Collapsing When using a function template or class template (via C++17 CTAD) **without explicitly specifying ``, leaving it to the compiler to deduce `T` from the passed arguments**, the process is called **Template Argument Deduction**. For example, when calling `compare(1, 0)` instead of `compare(1, 0)`, a function template's deduction rule splits into three cases depending on the parameter declaration form (`T`, `T&` / `const T&`, `T&&`): | Function Template Parameter Form | Preserves `const`? | Array/Function Decay? | Key Behavior | | :--- | :--- | :--- | :--- | | **By Value (`T`)** | Strips top-level `const` | Arrays/functions undergo pointer decay (`T*`) | Same as [Copying Objects]({{< relref "/programming/cpp/primer/variables-and-basic-types.md#copying-objects" >}}): creating an independent copy ignores top-level `const` on the argument. | | **By Reference (`T&` / `const T&`)** | Preserves low-level `const` | No pointer decay; arrays remain array references (`T (&)[N]`) | Passing two string literals of different lengths (`"hi"`, `"world"`) to `compare(const T&, const T&)` fails to compile (`T` is deduced as `char[3]` vs. `char[6]`). | | **Forwarding Reference (`T&&`)** | Preserves both value category and `const` | No pointer decay for lvalue arrays/functions | Via the special lvalue deduction rule and Reference Collapsing below, binds to both lvalues and rvalues while preserving their exact types. | ### Forwarding References (`T&&`) and Reference Collapsing Rules Template wrapper functions like [`make_unique`]({{< relref "/programming/cpp/primer/smart-pointers.md#2-stdunique_ptr-exclusive-ownership-and-stdmake_unique" >}}) and `emplace_back`, which receive parameters and pass them on to another function, must preserve both the constness and value category of each argument **with zero copy overhead**. Every other parameter form fails this requirement: | Function Template Parameter Declaration | Why It Fails for Perfect Forwarding | | :--- | :--- | | **`T arg`** | Creates a value copy immediately, wasting performance and losing reference identity | | **`T& arg`** | Cannot bind to rvalues like `42` or `"hello"`, causing a compile error | | **`const T& arg`** | Binds to both lvalues and rvalues, but forces `const` onto the parameter so forwarding to non-`const` references inside the template function is blocked, and rvalues invoke expensive copy constructors instead of move constructors | To account for both lvalues and rvalues, manually overloading `const T&` and `T&&` for every parameter would require $2^N$ functions for $N$ parameters. C++11 solves this in a single function template using **`T&&` attached directly to a deduced template parameter `T`**, known as a **Forwarding Reference**: 1. **Special lvalue Deduction Rule for `T&&` (`[temp.deduct.call]`):** - Under ordinary template deduction, passing an `int` lvalue would deduce `T` as `int`, turning the parameter into `int&&` and failing to compile because an rvalue reference cannot bind to an lvalue. - To solve this, C++11 introduced a dedicated deduction rule: **when a function template parameter has the exact form `T&&`, passing an rvalue deduces `T` as `int`, whereas passing an lvalue deduces `T` as an lvalue reference type `int&`.** - **Strict Form Requirement:** This rule activates **only** when `T` is a deduced parameter of that function template itself in the exact unadorned form `T&&`. Adding qualifiers or wrappers like `const T&&` or `std::vector&&`, or using a class template's `T` in a constructor parameter, disables the rule and leaves an ordinary rvalue reference. 2. **Reference Collapsing Rules:** - When `T` is deduced as `int&`, substituting into `T&&` produces `int& &&`, which the compiler collapses via these rules: - **`T& &`, `T& &&`, `T&& &` → all collapse to `T&`:** any lvalue reference `&` wins. - **`T&& &&` → collapses to `T&&`:** only when both are rvalue references. | Call Argument (`int` example) | Deduced `T` | Uncollapsed `T&&` | Final Collapsed Parameter Type | Result of `std::forward(ARG)` | | :--- | :--- | :--- | :--- | :--- | | **Non-`const` lvalue** | `int&` | `int& &&` | **`int&`** | Restores `int&`, preserving non-`const` lvalue | | **`const` lvalue** | `const int&` | `const int& &&` | **`const int&`** | Restores `const int&`, preserving `const` lvalue | | **rvalue (`42`)** | `int` | `int &&` | **`int&&`** | Restores `int&&`, preserving rvalue | Inside the function body, the named parameter `ARG` is always an lvalue expression, but whether `T` was deduced as a reference type `int&` or a value type `int` records whether the original argument was an lvalue or an rvalue. `std::forward(ARG)` inspects `T` to restore that exact value category, completing **Perfect Forwarding**. For code examples, see [Copy Elision & Move Semantics: `std::move` vs. `std::forward`]({{< relref "/programming/cpp/copy-elision-and-move-semantics.md#2-stdmove-vs-stdforward-move-semantics-vs-perfect-forwarding" >}}). --- ## 3. Variadic Templates (`Args...`) and `emplace_back` A **variadic template** accepts zero or more template type parameters and function arguments. Depending on where `...` appears, **placing `...` before a name packs elements together**, whereas **placing `...` after a pattern expands them**: - **`...` Before a Name — Packing (Parameter Pack Declaration):** - **Template Parameter Pack (`typename... Args`):** Packs zero or more types into `Args`. - **Function Parameter Pack (`Args&&... args`):** Packs zero or more function arguments into `args`. Despite the word "Function" in its name, it cannot be used in ordinary non-template functions and is valid only in function templates (or member functions of variadic class templates) that reference a Template Parameter Pack. - **`...` After an Expression — Unpacking (Pack Expansion):** - **`PATTERN...`:** Replicates the **entire pattern** to the left of `...` for each element in the pack, separated by commas `,`. - For example, `args...` expands to `arg1, arg2`, while `std::forward(args)...` expands to `std::forward(arg1), std::forward(arg2)`. Placing `...` inside the parentheses as `std::forward(args...)` is a compile error because it tries to pass multiple arguments into a single `std::forward` call (`std::forward(arg1, arg2)`). - **`sizeof...(Args)` Operator:** Returns the number of elements in a pack at compile time. ### 1. Recursive Variadic Function Pattern Variadic functions typically process the first argument `t` and recursively pass the remaining pack `rest...`. **A non-variadic base-case overload must be declared in scope before the variadic template to terminate the recursion**: ```cpp #include // 1. Base Case (must be declared before the variadic template): prints the final argument and ends recursion template std::ostream& print(std::ostream &os, const T &t) { return os << t; } // 2. Variadic Function Template: prints first argument t, then recursively expands rest... template std::ostream& print(std::ostream &os, const T &t, const Args&... rest) { os << t << ", "; return print(os, rest...); // Pack expansion peels off one argument at each step } ``` ### 2. Pack Expansion and How `emplace_back` Works Under the Hood Standard container `emplace_back` and `std::make_unique` construct elements directly in target memory without temporary objects by combining **variadic forwarding references (`Args&&...`)** with **pack expansion of `std::forward(args)...`**: ```cpp template class Vec { public: // Packs any number of constructor arguments into Args&&..., then expands the full std::forward pattern template void emplace_back(Args&&... args) { chk_n_alloc(); // Ensure capacity is available and reallocate if full alloc.construct(first_free++, std::forward(args)...); } }; // Example: Actual code instantiated by the compiler for vec.emplace_back(10, 'c') (Args deduced as int, char) // void emplace_back(int&& arg1, char&& arg2) { // chk_n_alloc(); // alloc.construct(first_free++, std::forward(arg1), std::forward(arg2)); // } ``` --- ## 4. Template Specialization When a generic primary template definition is unsuitable or inefficient for a specific type or type pattern, you can define a dedicated implementation via **Template Specialization**. ### 1. Why Are the Angle Brackets Empty in `template <>` for Full Specialization? - **Primary Template (`template `):** Indicates that **1 unbound template type parameter `T` remains**. - **Explicit Full Specialization (`template <>`):** Because `T` has been bound to a concrete type such as `std::string` or `int`, **0 unbound template parameters remain**, leaving `<>` empty. Omitting `template <>` while keeping `` on the function name is a syntax error. ```cpp // 1. Primary Template: converts any type C into a std::string via ostringstream template inline std::string Stringify(const C &value) { std::ostringstream o; o << value; return o.str(); } // 2. Explicit Full Specialization: // C is bound to std::string, so 0 unbound template parameters remain -> template <> template <> inline std::string Stringify(const std::string &s) { // can be omitted if deducible from parameters return "\"" + s + "\""; // Wrap strings in quotes } ``` ### 2. Full Specialization vs. Partial Specialization Depending on whether any unbound template parameters remain, specialization falls into two categories: - **Full Specialization (`template <>`):** Binds **every template parameter** of the primary template to a concrete type or value so that 0 unbound parameters remain, such as `struct hash` or `struct Map`. - **Partial Specialization (`template <...>`):** Narrows the primary template **while leaving one or more template parameters unbound**, so those remaining parameters are still listed inside `template <...>`. This takes two common forms: 1. **Fixing only a subset of parameters:** Given `template struct Map`, fixing `K` to `std::string` while leaving `V` unbound as `template struct Map`. 2. **Constraining a type pattern:** Specializing for all pointers (`T*`), references (`T&`, `T&&`), or fixed-size arrays (`T[N]`) rather than a single concrete type, such as `template struct hash`. Support across function templates and class templates differs as follows: | Aspect | Function Templates (`template void f(T)`) | Class / Struct Templates (`template struct Foo`) | | :--- | :--- | :--- | | **Full Specialization** | ✅ `template <> int compare(const char* const &p1, const char* const &p2)` | ✅ `template <> struct hash` | | **Partial Specialization** | ❌ Use **function overloading** instead | ✅ Supports both subset parameter binding and `T*`, `T&`, `T[N]` pattern specialization | - **Why can't we just put pointer logic in the primary `struct hash` or define another `struct hash` without ``?** 1. Value/object types (`T`), pointer types (`T*`), and array types (`T[N]`) require completely different hashing logic (e.g., casting a pointer address via `reinterpret_cast` fails to compile for non-pointer objects like `std::string`). 2. Unlike functions, **classes and structs cannot be overloaded**. Defining another `template struct hash` without `` causes a `redefinition of 'hash'` compile error; the `` pattern suffix tells the compiler to select this specialization specifically for pointer types. - **Partial specializations can have *more* template parameters than the primary template:** - Although the primary template `template struct hash` has only 1 parameter (`T`), partially specializing for a fixed-size array pattern `T[N]` requires 2 unbound parameters (the element type `T` and array length `N`): `template struct hash`. - **Compiler Matching Priority:** **1st: Full Specialization (`hash`) $\rightarrow$ 2nd: Partial Specialization (`hash`, `hash`) $\rightarrow$ 3rd: Primary Template (`hash`)** (most specific match wins). ```cpp // Complete structure combining Primary + Full + Partial Specializations (T*, T[N]) // [1] Primary Template (fallback for general types T) template struct hash { size_t operator()(const T &x) const { return x.CustomHash(); } }; // [2] Full Specialization (T fixed to int64_t -> 0 unbound parameters remain, so template <>) template <> struct hash { size_t operator()(int64_t x) const { return static_cast(x); } }; // [3] Partial Specialization #1: all pointer types (T* pattern -> pointee T still unbound, so template ) template struct hash { size_t operator()(T *x) const { return reinterpret_cast(x); } }; // [4] Partial Specialization #2: all fixed-size array types (T[N] pattern -> 2 unbound parameters T and N) template struct hash { size_t operator()(const T (&arr)[N]) const { size_t total = 0; hash elem_hasher; for (size_t i = 0; i < N; ++i) total ^= elem_hasher(arr[i]); return total; } }; ``` ### 3. Function Template Specialization (`template <>`) vs. Function Overloading: When to Use Which? To customize a function for a specific type, you can either write an **explicit specialization (`template <>`)** or a **plain non-template function overload**. For example, suppose we want `Stringify` to wrap C-style strings (`const char*`) in double quotes: ```cpp // Primary Template: converts any type C into a std::string via ostringstream template std::string Stringify(const C &value) { std::ostringstream o; o << value; return o.str(); } // Approach 1: template <> Explicit Specialization (tied to the Primary Template above) template <> std::string Stringify(const char* const &s) { // const C& with C substituted as const char* return "\"" + std::string(s) + "\""; } // Approach 2: Plain Function Overload (standalone non-template function without template <>) std::string Stringify(const char *s) { return "\"" + std::string(s) + "\""; } ``` The two approaches behave differently depending on how the function is called: - **When `<...>` is explicitly specified at the call site (`Stringify("hello")`):** - Writing `` after the function name instructs the compiler to **exclude plain non-template overloads (Approach 2) completely** and search only among `template` declarations. Thus, if you only wrote Approach 2, it is skipped and the **Primary Template** gets called (`"hello"`), whereas **Approach 1** (`template <>`) belongs to that `template` and gets called as expected (`"\"hello\""`). - **Why is plain function overloading still preferred over `template <>` for ordinary calls without `<...>` (`Stringify("hello")`)?** 1. **No Implicit Conversions or Pointer Decay on Template Specializations:** - **Approach 1 (`template <>` specialization):** Does not participate as an independent overload candidate; it is checked **only after type deduction on the Primary Template finishes**. Calling `Stringify("hello")` passes a string literal whose actual type is `const char[6]`. Because the Primary Template parameter is a reference (`const C&`), no pointer decay occurs and `C` is deduced as `char[6]`. The compiler only checks whether a specialization exists for `char[6]` without attempting any conversion to `const char*`, so Approach 1 is ignored and the **Primary Template** is called (`"hello"`). - **Approach 2 (plain function overload):** Participates directly in first-round overload resolution where implicit conversions and pointer decay apply. `const char[6]` decays to `const char*` to match Approach 2, and when a plain function ties in conversion rank (Exact Match) with `Stringify`, C++ prefers the **non-template function over the template**, calling **Approach 2** as intended (`"\"hello\""`). 2. **Function Templates Cannot Be Partially Specialized:** Customizing for pointers (`T*`) or containers (`std::vector`) requires function overloading anyway. 3. **Overload Resolution Pitfalls (Herb Sutter's Guideline):** For the same reason as #1, explicit function template specializations do not participate directly in first-round overload resolution and are only considered after their primary template is selected, so they can be unexpectedly bypassed when mixed with other overloads such as `template void f(T*)`. #### Practical Rule of Thumb: When Must You Use `template <>`? | Scenario | Recommended Approach | Why | | :--- | :--- | :--- | | **Functions where types are deduced from arguments** (`Stringify("hello")`, `compare(1, 0)`) | **Function Overloading** | Supports implicit conversions and predictable overload resolution | | **Class / Struct Templates** (`std::hash`, Type Traits) | **`template <>` Full / Partial Specialization** | Classes cannot be overloaded; specialization is the only mechanism | | **Functions with identical parameter types that differ only in return type ``** (`Parse("8080")`, `Parse("3.14")`) | **`template <>` Explicit Specialization** | C++ **forbids overloading functions that differ only by return type** — plain overloads fail to compile, so `template <>` is required | ```cpp // When parameters are identical (std::string_view) and only the return type T differs: // Plain overloads fail to compile, so template <> is required template T Parse(std::string_view s); template <> int Parse(std::string_view s) { return std::stoi(std::string(s)); } template <> double Parse(std::string_view s) { return std::stod(std::string(s)); } // Call site: int port = Parse("8080"); double pi = Parse("3.14"); ```