C++ Templates: Function & Class Templates for High-Performance Generic Code

Templates are the foundation of Generic Programming in C++. A template allows you to write a single blueprint for a function or class that works seamlessly across any data type without duplicating code.

1. Function Template Example

#include <iostream>
#include <string>

// Generic template function
template <typename T>
T getMaximum(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    std::cout << "Max int:    " << getMaximum(15, 42) << "\n";           // Instantiates getMaximum<int>
    std::cout << "Max double: " << getMaximum(3.14, 2.71) << "\n";       // Instantiates getMaximum<double>
    std::cout << "Max string: " << getMaximum<std::string>("Apple", "Zebra") << "\n"; // Zebra
    return 0;
}

2. Generic Class Template

#include <iostream>

template <typename T, int Capacity>
class FixedStack {
private:
    T elements[Capacity];
    int topIndex = -1;

public:
    void push(const T& item) {
        if (topIndex < Capacity - 1) {
            elements[++topIndex] = item;
        }
    }
    T pop() {
        return elements[topIndex--];
    }
};

int main() {
    FixedStack<int, 10> intStack;
    intStack.push(100);
    std::cout << "Popped: " << intStack.pop() << "\n";
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between 'typename' and 'class' in template declarations?

In template parameter declarations (e.g., template vs template ), there is absolutely no difference; both are 100% interchangeable. 'typename' is preferred in modern C++ because it clearly indicates that any type (primitive or class) can be supplied.

Q2. Do C++ templates incur any runtime performance penalty?

Zero! Templates are a purely compile-time feature. The compiler generates concrete, specialized machine code for each unique type instantiated, allowing the optimizer to aggressively inline operations without any runtime indirection.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

Template Specialization

Full and partial specialization for specific data types.

STL Overview

How templates power the C++ Standard Template Library.

C++20 Concepts

Adding compile-time constraints to templates.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!