ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

C++ Tutorial• 7 min read

Templates & Generic Programming

Function templates, class templates, and compile-time code generation

Templates allow you to write generic functions and classes that work with arbitrary data types without duplicating source code, instantiated at compile-time for zero runtime overhead.

Template Code Generation

Function Template: template <typename T> T maxVal(T a, T b) { return (a > b) ? a : b; }.

The compiler generates distinct specialized machine code versions for every type used (maxVal<int>, maxVal<double>).

Class Templates: Powers containers like std::vector<T>.

Generic Stack Template Class
#include <iostream>
#include <vector>

template <typename T>
class Stack {
private:
    std::vector<T> elements;
public:
    void push(const T &item) { elements.push_back(item); }
    T pop() {
        T top = elements.back();
        elements.pop_back();
        return top;
    }
};

int main() {
    Stack<int> intStack;
    intStack.push(10);
    intStack.push(20);

    Stack<std::string> strStack;
    strStack.push("Codexia");
    std::cout << strStack.pop() << std::endl;
    return 0;
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

When are C++ templates compiled and instantiated into concrete machine code for specific types?