Skip to content
    SeaCode
    Learning tracksCode ArenaWorkshops & EventsInstructors
    Log inSign up
    C++C++

    C++ fundamentals

    • Your first C++ program
    • Variables and types
    • Operators and input
    • Conditions: if and switch
    • Loops

    Functions and collections

    • Functions
    • References: by value or by reference?
    • Strings and arrays
    • std::vector
    • map, set and unordered_map

    Memory and pointers

    • Pointers
    • Stack, heap, new and delete
    • Smart pointers and RAII

    Classes and OOP

    • struct and class
    • Constructors and destructors
    • Inheritance and virtual functions
    • Templates

    The STL and professional C++

    • Algorithms and lambdas
    • Exceptions
    • Recursion
    • Project: a grade book
    C++

    Classes and OOP · Lesson 17 of 21

    Templates

    Write a function or class once and use it with any type.

    10 minutes2 games

    Instead of writing largest for int, double and string, write it once as a template. The compiler generates a version for each type you use, at compile time, so it's as fast as hand-written code. That's exactly how std::vector<T> and std::map<K, V> are built.

    C++
    #include <iostream>
    #include <string>
    #include <vector>
    
    template <typename T>
    T largest(const std::vector<T>& items) {
        T best = items.at(0);
        for (const T& x : items) {
            if (x > best) best = x;
        }
        return best;
    }
    
    int main() {
        std::cout << largest(std::vector<int>{3, 9, 4}) << "\n";
        std::cout << largest(std::vector<double>{2.5, 1.5}) << "\n";
        std::cout << largest(std::vector<std::string>{"pear", "apple", "zebra"}) << "\n";
        return 0;
    }

    template <typename T> T largest(...)

    largest(vector<int>) → compiler generates an int version

    largest(vector<string>) → a string version

    A template isn't running code; it's a recipe the compiler cooks from.

    Class templates

    C++
    #include <iostream>
    #include <string>
    
    template <typename K, typename V>
    struct Pair {
        K key;
        V value;
        void print() const { std::cout << key << " => " << value << "\n"; }
    };
    
    template <typename T, int N>
    struct FixedStack {
        T items[N];
        int count = 0;
        bool push(const T& x) {
            if (count == N) return false;
            items[count++] = x;
            return true;
        }
    };
    
    int main() {
        Pair<std::string, int> p{"xp", 320};
        p.print();
    
        FixedStack<char, 2> s;
        std::cout << s.push('a') << s.push('b') << s.push('c') << "\n";
        return 0;
    }

    Important

    A template assumes the type supports what's used inside: largest needs >. Try it on a type without > and you get a very long compiler error. Templates are usually written entirely in .h files because the compiler must see the whole code to generate versions. (C++20 added concepts to state these requirements explicitly with clearer messages.)

    Complete the code

    Complete the template that swaps two values of any type.

    #include <iostream>
     <typename T>
    void swapAny(T& a, T& b) {
         temp = a;
        a = b;
        b = temp;
    }
    int main() {
        int x = 1, y = 2;
        swapAny(x, y);
        std::cout << x << y << "\n";
    }

    Interview question

    How do templates differ from virtual functions? Both are polymorphism, right?

    Exercise

    Write a template T sumAll(const std::vector<T>& v) returning the sum, and use it with {1, 2, 3} and {0.5, 0.25}. Two lines of output: 6 and 0.75.

    Expected output:
    6
    0.75
    C++
    #include <iostream>
    #include <vector>
    
    
    int main() {
        std::cout << sumAll(std::vector<int>{1, 2, 3}) << "\n";
        std::cout << sumAll(std::vector<double>{0.5, 0.25}) << "\n";
        return 0;
    }

    Learn more from

    • learncpp: Function templateslearncpp.com
    • cppreference: Templatesen.cppreference.com
    • isocpp FAQ: Templatesisocpp.org

    Played 0 of 2 games

    Sign in to save your progress and earn XP.

    PreviousInheritance and virtual functionsNextAlgorithms and lambdas
    SeaCode

    Learn to code for real, online or at our branch in front of Cairo University, Giza.

    Learn

    • All courses
    • Interactive tutorials
    • Interview practice problems
    • Mock interview
    • Learning tracks
    • Code Arena
    • Workshops & Events
    • Knowledge library
    • Team projects

    Your account

    • Log in
    • Sign up
    • Learning plan
    • Certificates
    • Site map

    Contact us

    • WhatsApp
    • 010 9094 1104
    • In front of Cairo University, Giza

    © 2026 SeaCode. All rights reserved.