Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. The problem: one body, three copies
    4. Writing it once: template <typename T>
    5. How the compiler picks T
    6. Naming the type yourself
    7. Several template parameters
    8. Shorter templates: auto parameters
    9. Instantiation: a version for each type
    10. Reading template error messages
    11. Which one should I use?
    12. Under the hood
    13. Common pitfalls
    14. Two arguments of different types
    15. String literals aren’t std::string
    16. Try it yourself

    Module 6 · Generic code

    6.1Function templates

    Write a function once and use it with many types. Learn how the compiler works out the type, when to name it yourself, what it generates for each type, and how to read the errors.

    About 25 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. The problem: one body, three copies
    4. Writing it once: template <typename T>
    5. How the compiler picks T
    6. Naming the type yourself
    7. Several template parameters
    8. Shorter templates: auto parameters
    9. Instantiation: a version for each type
    10. Reading template error messages
    11. Which one should I use?
    12. Under the hood
    13. Common pitfalls
    14. Two arguments of different types
    15. String literals aren’t std::string
    16. Try it yourself

    Key terms

    template
    A pattern for a function or a type, with placeholders that the compiler fills in. Code written this way, once for many types, is called generic code.
    function template
    A function written with template <typename T> in front. The compiler makes a real function from it for each type you use.
    template parameter
    A placeholder in a template, like T in template <typename T>. typename (or class, which means the same here) says it stands for a type.
    template argument
    The real type that fills a template parameter, like int in larger<int>. Written in angle brackets, it's an explicit template argument.
    template argument deduction
    The compiler working out the template arguments from the types of the function's arguments.
    instantiation
    The compiler writing a real function from a template, for one set of template arguments.
    abbreviated function template
    A function with auto parameters, like void report(const auto& x). Each auto is a template parameter of its own.
    weak symbol (W)
    A symbol that several object files may define. The linker keeps one copy and drops the rest.

    This module is about generic code: writing a function or a type once and using it with many types, and moving work from run time to compile time. It starts with functions. In Functions you wrote larger twice, once for int and once for double, with the same body. A third type means a third copy, and a bug in one copy has to be fixed in all of them. A function template lets you write the body once and leave the type as a placeholder. The compiler writes each version for you.

    In 30 seconds

    • template <typename T> T larger(T a, T b) is a function template: a pattern with a placeholder type T.
    • At each call, the compiler works out T from the arguments. You can also name it: larger<double>(3, 2.5).
    • For each type you use, the compiler writes a real function from the pattern. This is called instantiation, and it’s when type errors show up.
    • auto parameters are a short way to write a template: void report(const auto& value).

    The problem: one body, three copies

    Here is larger for three types. The bodies are identical; only the types change.

    #include <print>
    #include <string>
    
    int larger(int a, int b) {
        return a > b ? a : b;
    }
    
    double larger(double a, double b) {
        return a > b ? a : b;
    }
    
    std::string larger(std::string a, std::string b) {
        return a > b ? a : b;
    }
    
    int main() {
        std::string x = "ACGT";
        std::string y = "TTAG";
        std::println("{} {} {}", larger(3, 8), larger(2.5, 1.5), larger(x, y));
    }

    Output

    8 2.5 TTAG

    > on two std::strings compares them in dictionary order, so "TTAG" is the larger one. Every new type you want to compare needs another copy of the same three lines.

    Writing it once: template <typename T>

    Put template <typename T> in front of the function, and use T wherever a type changes. T is a template parameter: a name for a type that will be filled in later. typename says that T stands for a type. You’ll also see template <class T> in older code; in this place, class and typename mean the same thing.

    #include <print>
    #include <string>
    
    template <typename T>
    T larger(T a, T b) {
        return a > b ? a : b;
    }
    
    int main() {
        std::string x = "ACGT";
        std::string y = "TTAG";
        std::println("{} {} {}", larger(3, 8), larger(2.5, 1.5), larger(x, y));
        std::println("{}", larger('A', 'G'));
    }

    Output

    8 2.5 TTAG
    G

    One definition now covers int, double, std::string and char, and any other type that has a >. The name T is a convention, not a rule; any name works.

    How the compiler picks T

    You never said what T is. At each call, the compiler looks at the types of the arguments and matches them against the parameters. In larger(3, 8) both arguments are int, so T is int. This is template argument deduction. It looks only at the arguments, the same way overloading does; what you do with the result doesn’t matter.

    Deduction needs every match to agree. If one argument says int and the other says double, it fails. Common pitfalls shows that error.

    Naming the type yourself

    You can skip deduction and write the template argument yourself, in angle brackets after the name. Then the arguments are converted to that type, like for any ordinary function:

    #include <print>
    
    template <typename T>
    T larger(T a, T b) {
        return a > b ? a : b;
    }
    
    int main() {
        std::println("{}", larger<double>(3, 2.5));
    }

    Output

    3

    larger<double> is a function that takes two doubles, so the 3 becomes 3.0. It prints as 3 because std::println leaves off a fraction of zero.

    Several template parameters

    A template can have as many parameters as it needs. Sometimes one of them can’t be deduced, because it appears only in the return type. This mean lets the caller choose the type of the result, and deduces the element type from the vector:

    #include <print>
    #include <vector>
    
    template <typename Result, typename T>
    Result mean(const std::vector<T>& values) {
        Result total{};
        for (const T& v : values) {
            total += v;
        }
        return total / static_cast<Result>(values.size());
    }
    
    int main() {
        std::vector<int> counts = {1, 2, 4, 6};
        std::println("{}", mean<double>(counts));
        std::println("{}", mean<int>(counts));
    }

    Output

    3.25
    3

    In mean<double>(counts), you give Result and the compiler deduces T as int by matching std::vector<int> against std::vector<T>. Explicit arguments fill the parameters from the left, which is why Result comes first. Plain mean(counts) doesn’t compile: nothing in the arguments says what Result should be.

    Result total{}; gives total its type’s empty value: 0 for numbers, an empty string for std::string. In a template you don’t know the type, so empty braces are the way to start from zero.

    Shorter templates: auto parameters

    A parameter written as auto makes the function a template, without the template line. This is an abbreviated function template. Each auto gets its own template parameter, so the two parameters here can have different types:

    #include <print>
    #include <string>
    #include <vector>
    
    void report(const auto& name, const auto& value) {
        std::println("{:>8}: {}", name, value);
    }
    
    int main() {
        report("reads", 1200);
        report("gc", 0.42);
        std::vector<int> lengths = {150, 98, 151};
        report(std::string{"lengths"}, lengths);
    }

    Output

       reads: 1200
          gc: 0.42
     lengths: [150, 98, 151]

    report means the same as template <typename A, typename B> void report(const A& name, const B& value). Use auto parameters when each parameter can be any type on its own. When two parameters must have the same type, as in larger, or when you need to write the type’s name in the body, use template <typename T>.

    Instantiation: a version for each type

    A template isn’t a function yet; it’s a pattern. When you call larger(3, 8), the compiler replaces T with int everywhere in the pattern and compiles the result as an ordinary function, larger<int>. This is instantiation. A second call with int arguments uses the same function. A call with double arguments makes another one. A template you never call produces no code at all.

    You can see that the versions are separate functions. A static local variable belongs to one function, so each version gets its own counter:

    #include <print>
    
    template <typename T>
    void log_call(T value) {
        static int calls = 0; // one counter per version
        ++calls;
        std::println("call {} with {}", calls, value);
    }
    
    int main() {
        log_call(1);
        log_call(2);
        log_call(0.5); // a new version: log_call<double>
        log_call(3);
    }

    Output

    call 1 with 1
    call 2 with 2
    call 1 with 0.5
    call 3 with 3

    Stack, heap and lifetime introduced static locals. log_call<int> and log_call<double> each have one, so the double call starts counting from 1.

    Key ideaThe compiler writes the overloads for you

    After instantiation, a template call is a call to an ordinary function, exactly like the overloads you’d have written by hand. Templates cost nothing extra when the program runs.

    Reading template error messages

    The compiler checks the parts of a template’s body that use T only when it instantiates it, because until then it doesn’t know what T is. So a type that’s missing something the body uses fails at instantiation, and the error points inside the template. Here, Read has no >:

    #include <print>
    #include <string>
    
    template <typename T>
    T larger(T a, T b) {
        return a > b ? a : b;
    }
    
    struct Read {
        std::string id;
        int length;
    };
    
    int main() {
        Read r1{"r1", 150};
        Read r2{"r2", 98};
        Read best = larger(r1, r2);
        std::println("{}", best.id);
    }

    The compiler rejects this

    main.cpp: In instantiation of ‘T larger(T, T) [with T = Read]’:
    main.cpp:17:23:   required from here
       17 |     Read best = larger(r1, r2);
          |                 ~~~~~~^~~~~~~~
    main.cpp:6:14: error: no match for ‘operator>’ (operand types are ‘Read’ and ‘Read’)
        6 |     return a > b ? a : b;
          |            ~~^~~

    GCC’s message has three parts. Read them in this order:

    1. In instantiation of … [with T = Read]: which version failed, and what T was.
    2. required from here: the line in your code that asked for that version. This is usually where the fix goes.
    3. error: no match for …: what went wrong inside the template body. The template is fine; the type is missing something it needs.

    Here the fix is to say what “larger” means for a read. To compare lengths, call larger(r1.length, r2.length). To compare whole reads with >, give Read that operator; Operators and comparisons shows how.

    Errors from deep inside standard library templates can run to pages, with many “required from” lines. Look for the first “required from here” in your own file and start there. Concepts, two lessons on, shows how a template can say up front what its type needs, so the error appears at your call and names the missing requirement.

    Which one should I use?

    WhatWhenWhyHow
    OverloadsEach type needs a different body.The compiler picks the right body; each one is written for its type.int area(Square s) and int area(Circle c)
    Function templateThe body is the same for every type, and parameters must share a type or you need the type’s name.One definition to read, test and fix.template <typename T> T larger(T a, T b)
    auto parametersShort helpers where each parameter can be any type.Less to write than a template line.void report(const auto& name, const auto& value)
    Explicit template argumentsA parameter can’t be deduced, or you want the arguments converted to one type.You decide the type instead of the arguments.mean<double>(counts), larger<double>(3, 2.5)

    Rule of thumb: when you’re about to copy a function and change only its types, write a template instead.

    Under the hood

    Each instantiation is compiled into its own machine code, with its own symbol. How a C++ program is built used nm -C to list the symbols in an object file. Compile a file that calls larger(3, 8) and larger(2.5, 1.5), and list it:

    g++ -std=c++23 -c larger.cpp -o larger.o
    nm -C larger.o | grep larger
    # 0000000000000000 W double larger<double>(double, double)
    # 0000000000000000 W int larger<int>(int, int)
    

    The two # lines show what it prints with GCC on Linux; the zeros are positions inside the object file. There’s one function per type you used, and none for the types you didn’t. The W means a weak symbol: every file that calls larger<int> compiles its own copy, and the linker keeps one and drops the rest. An ordinary function shows up with the letter T (for “text”, the code section), and two files that define the same ordinary function make a link error.

    That’s also why templates live in headers. To write larger<int>, the compiler needs the template’s whole body in the file it’s compiling, not just a declaration. So a template’s definition goes in a header that every file using it includes, and the weak symbols keep the copies from clashing. Module 8 covers headers and multi-file projects.

    PerformanceMore types, more code

    Templates are as fast as handwritten functions, but each type you use adds another copy of the machine code, and the compiler has to build each one. A template used with dozens of types can make a program bigger and slower to compile. For small functions like larger, it doesn’t matter.

    Common pitfalls

    Two arguments of different types

    With one T for both parameters, larger(3, 2.5) asks for T to be int and double at once. Deduction doesn’t convert anything, so it fails:

    #include <print>
    
    template <typename T>
    T larger(T a, T b) {
        return a > b ? a : b;
    }
    
    int main() {
        std::println("{}", larger(3, 2.5));
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:9:30: error: no matching function for call to ‘larger(int, double)’
        9 |     std::println("{}", larger(3, 2.5));
          |                        ~~~~~~^~~~~~~~
    main.cpp:9:30: note: there is 1 candidate
    main.cpp:4:3: note: candidate 1: ‘template<class T> T larger(T, T)’
        4 | T larger(T a, T b) {
          |   ^~~~~~
    main.cpp:4:3: note: template argument deduction/substitution failed:
    main.cpp:9:30: note:   deduced conflicting types for parameter ‘T’ (‘int’ and ‘double’)
        9 |     std::println("{}", larger(3, 2.5));
          |                        ~~~~~~^~~~~~~~

    With the two overloads from Functions, the same call was “ambiguous”. Here the message lists the template as a candidate and says why it was skipped: the deduced types conflict. Make the types match with larger(3.0, 2.5), or name the type with larger<double>(3, 2.5).

    String literals aren’t std::string

    A string literal like "GATTACA" is an array of char. Passed by value, it decays to a pointer to its first character, as Arrays and span showed. So T becomes const char*, and larger compares two addresses, not two pieces of text:

    #include <print>
    
    template <typename T>
    T larger(T a, T b) {
        return a > b ? a : b;
    }
    
    int main() {
        auto best = larger("GATTACA", "CAT");
        std::println("{}", best.size());
    }

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:10:29: error: request for member ‘size’ in ‘best’, which is of non-class type ‘const char*’
       10 |     std::println("{}", best.size());
          |                             ^~~~

    The call itself compiles; .size() is what fails, because best is a pointer. If you printed best instead, you’d get whichever literal the compiler happened to place at the higher address. The standard doesn’t say which one that is, and it has nothing to do with dictionary order. Name the type, and both literals become std::strings:

    #include <print>
    #include <string>
    
    template <typename T>
    T larger(T a, T b) {
        return a > b ? a : b;
    }
    
    int main() {
        std::string best = larger<std::string>("GATTACA", "CAT");
        std::println("{} {}", best, best.size());
    }

    Output

    GATTACA 7

    Common pitfallDeduction doesn't convert

    When the compiler deduces T, it uses the argument types exactly as they are: int stays int, and a string literal stays a char array or pointer. Conversions happen only after T is known, so name the type when you want one.

    Try it yourself

    Try it yourself

    count_equal counts how many items in a vector equal a target, but only for int. Turn it into a function template so it also counts bases in a std::vector<char> and k-mers (short pieces of DNA) in a std::vector<std::string>. The program should print 2, 3 and 2.

    #include <print>
    #include <vector>
    
    int count_equal(const std::vector<int>& items, int target) {
        int count = 0;
        for (int item : items) {
            if (item == target) {
                ++count;
            }
        }
        return count;
    }
    
    int main() {
        std::vector<int> scores = {90, 75, 90, 60};
        std::println("{}", count_equal(scores, 90));
        // Then count 'A' in {'G', 'A', 'T', 'T', 'A', 'C', 'A'},
        // and "GA" in {"GA", "AT", "GA"}.
    }

    Expected output

    2
    3
    2
    Show a hint

    Write template <typename T> above the function, then replace int with T in the vector's element type, the target and the loop variable. Keep the return type int: it's a count.

    Show a solution
    #include <print>
    #include <string>
    #include <vector>
    
    template <typename T>
    int count_equal(const std::vector<T>& items, const T& target) {
        int count = 0;
        for (const T& item : items) {
            if (item == target) {
                ++count;
            }
        }
        return count;
    }
    
    int main() {
        std::vector<int> scores = {90, 75, 90, 60};
        std::println("{}", count_equal(scores, 90));
        std::vector<char> bases = {'G', 'A', 'T', 'T', 'A', 'C', 'A'};
        std::println("{}", count_equal(bases, 'A'));
        std::vector<std::string> kmers = {"GA", "AT", "GA"};
        std::println("{}", count_equal(kmers, std::string{"GA"}));
    }

    T is deduced from both arguments: std::vector<char> and 'A' both say char. For the k-mers, the target must be a std::string too. A plain GA literal would make the second argument a char array while the vector says std::string, and deduction would fail with conflicting types.