Lesson 11 • Expert

    Templates

    Write generic, type-safe code that works with any data type — the foundation of the entire C++ Standard Library.

    What You'll Learn

    • Function templates and type deduction
    • Class templates for generic containers
    • Template specialization
    • Non-type template parameters

    What Are Templates?

    Templates let you write code that works with any type without rewriting it. Instead of creating maxInt(), maxDouble(), and maxString(), you write one max<T>() template.

    Think of templates like a form letter: "Dear [NAME], your order #[NUMBER] is ready." The template defines the structure; the compiler fills in the blanks with concrete types.

    template <typename T>    // T is a placeholder for any type
    T maxOf(T a, T b) {
        return (a > b) ? a : b;
    }
    
    // Compiler generates:
    // int maxOf(int, int)       — when called with ints
    // double maxOf(double, double) — when called with doubles

    Function Templates

    Create generic max, pair display, and template specialization

    Try it Yourself »
    C++
    #include <iostream>
    #include <string>
    using namespace std;
    
    // Function template — works with ANY type
    template <typename T>
    T maxOf(T a, T b) {
        return (a > b) ? a : b;
    }
    
    // Template with multiple type parameters
    template <typename T, typename U>
    void displayPair(T first, U second) {
        cout << "(" << first << ", " << second << ")" << endl;
    }
    
    // Template with default type
    template <typename T = int>
    T add(T a, T b) {
        return a + b;
    }
    
    // Template specialization for strings
    template <>
    
    ...

    Class Templates: Generic Stack

    Build a reusable Stack that works with int, string, and double

    Try it Yourself »
    C++
    #include <iostream>
    #include <string>
    using namespace std;
    
    // Class template — a generic container
    template <typename T>
    class Stack {
    private:
        T data[100];
        int top;
        
    public:
        Stack() : top(-1) {}
        
        void push(T value) {
            if (top >= 99) {
                cout << "Stack overflow!" << endl;
                return;
            }
            data[++top] = value;
        }
        
        T pop() {
            if (isEmpty()) {
                cout << "Stack underflow!" << endl;
                return T();  // 
    ...

    Pair Template & Non-Type Parameters

    Create a generic Pair class and a fixed-size array with compile-time size

    Try it Yourself »
    C++
    #include <iostream>
    #include <string>
    using namespace std;
    
    // Generic Pair class
    template <typename K, typename V>
    class Pair {
    private:
        K key;
        V value;
        
    public:
        Pair(K k, V v) : key(k), value(v) {}
        
        K getKey() const { return key; }
        V getValue() const { return value; }
        
        void setKey(K k) { key = k; }
        void setValue(V v) { value = v; }
        
        void display() const {
            cout << key << " => " << value << endl;
        }
    };
    
    // Generic function using Pair
    tem
    ...

    Common Mistakes

    ⚠️ Template definitions in .cpp: Templates must be fully defined in header files. The compiler needs to see the full code to generate type-specific versions.

    ⚠️ Type mismatch: maxOf(5, 3.14) fails — the compiler can't deduce T as both int and double. Use maxOf<double>(5, 3.14).

    ⚠️ Cryptic error messages: Template errors can be long and confusing. Read from the bottom up and focus on the first error.

    Pro Tips

    💡 Use auto with templates: auto result = maxOf(5, 3); lets the compiler figure out the return type.

    💡 constexpr templates: Mark template functions constexpr when possible for compile-time evaluation.

    💡 The STL uses templates everywhere: vector<T>, map<K,V>, sort() — templates are the backbone of the Standard Library.

    Lesson Complete!

    You can now write generic, reusable code with templates. Next up: Standard Template Library — the powerful collection of containers and algorithms built on templates.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service