Templates enable generic programming — write once, compile for any type. Instantiations happen at compile time with full optimization.

Function Templates

  template<typename T>
T max(T a, T b) { return a > b ? a : b; }

int m1 = max(3, 5);
double m2 = max(3.14, 2.71);
  

Class Templates

  template<typename T>
class Stack {
    std::vector<T> data_;
public:
    void push(const T& val) { data_.push_back(val); }
    T pop() { T v = data_.back(); data_.pop_back(); return v; }
};

Stack<int> intStack;
  

Specialization

  template<>
class Stack<bool> {
    // optimized bit-packed implementation
};
  

Variadic Templates

  template<typename... Args>
void log(Args&&... args) {
    (std::cout << ... << args) << '\n';  // C++17 fold
}
log("x=", 42, ", y=", 3.14);
  

Concepts (C++20)

  #include <concepts
template<std::integral T>
T gcd(T a, T b) {
    while (b) { T t = b; b = a % b; a = t; }
    return a;
}
  

Common Pitfalls

  • Ignoring compiler or linter warnings until they become production bugs.
  • Skipping error handling on I/O, allocation, and network operations.
  • Using outdated patterns when modern idioms exist in your language version.
  • Testing only the happy path without edge cases and failure modes.

Best Practices

  • Write tests alongside implementation, not after.
  • Prefer explicit, readable code over clever one-liners.
  • Use the standard library before reaching for third-party dependencies.
  • Profile before optimizing; measure after.
  • Document public APIs and non-obvious invariants.

Memory and Performance Notes

Each template instantiation generates code — template bloat increases binary size.

Exercise

Implement a generic pair<T,U> class template with first and second members.

Hint: Use concepts to constrain template parameters and get clearer error messages.

Real-World Application

Production codebases combine these fundamentals with logging, metrics, and error recovery. Study mature open-source projects in this language for idiomatic patterns.

Summary

Master this topic through hands-on practice before advancing to the next section in the learning path.

Debugging Checklist

  1. Reproduce with minimal input.
  2. Read error messages completely.
  3. Binary-search the problem space by commenting out code.
  4. Compare against a known-good reference implementation.
  5. Write a regression test once fixed.

Quick Reference

Review the code examples on this page and type them manually — muscle memory accelerates learning.

Further Reading

C++ Core Guidelines, cppreference.com, and Effective Modern C++ by Scott Meyers.

Real-World Context

These patterns appear in Chromium, Unreal Engine, PostgreSQL, and countless production systems.

Additional Examples

Consider how this topic applies in a larger project:

  // Break the problem into smaller functions
// Test each function independently
// Integrate incrementally
  

Working through variations of the examples above builds deeper understanding than reading alone.

Interview and Review Questions

  1. Explain the core concept of this topic in your own words.
  2. What happens when this code runs with edge-case input (empty, null, zero, max value)?
  3. How would you debug a bug related to this topic in production?
  4. What are the performance implications of the approach shown here?
  5. How does this feature compare to the equivalent in another language you know?