Skip to main content
C++ Fundamentals for Beginners to Advanced
CHAPTER 20 Beginner

Templates in C++

Updated: May 17, 2026
5 min read

# CHAPTER 20

Templates in C++

1. Introduction

If you want to write a function that finds the maximum of two integers, you write int max(int a, int b). But what if you also need to compare floats? You'd have to overload the function float max(float a, float b). What if you want to compare characters? Overloading every possible type violates the DRY (Don't Repeat Yourself) principle. Templates solve this.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand the concept of Generic Programming.
  • Write Function Templates.
  • Write Class Templates.
  • Understand Template Specialization.

3. Generic Programming

Generic programming is a style of programming where algorithms are written in terms of types to-be-specified-later. In C++, this is achieved using the template keyword.

4. Function Templates

A function template tells the compiler how to generate a function for *any* data type.

Syntax: template <typename T>

cpp
123456789101112131415161718192021
#include <iostream>
using namespace std;

// 'T' acts as a placeholder for ANY data type (int, float, string, etc.)
template <typename T>
T myMax(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    // The compiler generates an int version of myMax
    cout << myMax<int>(10, 20) << endl; 
    
    // The compiler generates a float version of myMax
    cout << myMax<float>(3.14f, 5.99f) << endl; 
    
    // Modern C++ can often deduce the type automatically!
    cout << myMax(&#039;A&#039;, &#039;Z&#039;) << endl; 

    return 0;
}

5. Multiple Template Parameters

Templates can have more than one generic type.
cpp
1234567891011
template <typename T, typename U>
void printData(T data1, U data2) {
    cout << "Data 1: " << data1 << endl;
    cout << "Data 2: " << data2 << endl;
}

int main() {
    // T becomes string, U becomes int
    printData<string, int>("Score", 100); 
    return 0;
}

6. Class Templates

Just as you can make functions generic, you can make entire classes generic. This is extremely useful for building data structures (like Stacks or Arrays) that can hold *any* type of data.
cpp
12345678910111213141516171819202122232425
template <typename T>
class Box {
  private:
    T content;
  public:
    void setContent(T newContent) {
        content = newContent;
    }
    T getContent() {
        return content;
    }
};

int main() {
    Box<int> intBox; // A Box that holds integers
    intBox.setContent(123);
    
    Box<string> stringBox; // A Box that holds strings
    stringBox.setContent("Secret Message");
    
    cout << intBox.getContent() << endl;
    cout << stringBox.getContent() << endl;

    return 0;
}

7. Template Specialization

Sometimes, you write a generic template, but you want it to behave *differently* if a specific data type is passed. This is called specialization.
cpp
12345678910111213141516
template <typename T>
void print(T data) {
    cout << "Generic: " << data << endl;
}

// Specialization for chars
template <>
void print<char>(char data) {
    cout << "Character specialized: " << data << endl;
}

int main() {
    print(100);   // Calls generic
    print(&#039;X&#039;);   // Calls specialized!
    return 0;
}

8. Memory-Level Explanation

Templates are NOT code. They are blueprints for code. If you write a template but never use it in main(), it uses 0 bytes of memory.

If you call myMax<int> and myMax<float>, the compiler writes the actual machine code for TWO separate functions behind the scenes. This is called Template Instantiation. This makes templates extremely fast (no runtime overhead), but it can increase the final .exe file size (Code Bloat).

9. Common Mistakes

  • Putting template definitions in .cpp files: Because the compiler needs to generate the code at the exact moment the template is called in main(), template *definitions* must usually be placed entirely in the .h header file.
  • Forgetting <Type> in Class Templates: You cannot write Box b;. You MUST specify the type: Box<int> b;.

10. Exercises

  1. 1. Write a function template swapData that swaps two variables of any type. Test it with integers and strings.
  1. 2. Write a class template Pair that holds two variables of the same generic type, with a method getLarger() that returns the larger of the two.

11. MCQ Quiz with Answers

Question 1

What is the main benefit of templates?

Question 2

Which keyword is used to declare a template parameter?

Question 3

If a template is never called, how much compiled machine code is generated for it?

Question 4

What is Template Instantiation?

Q5. Can a function template have multiple generic types (e.g., <typename T, typename U>)? a) Yes b) No Answer: a) Yes

Q6. When instantiating a Class Template, must you specify the data type in angle brackets? a) Yes (e.g., Box<int>) b) No Answer: a) Yes (e.g., Box<int>)

Question 7

What is Template Specialization?

Question 8

Where should template definitions typically be placed?

Question 9

What is a potential downside of heavy template usage?

Question 10

Can you use int as a generic type in myMax('A', 'Z')?

12. Interview Questions

  • Q: Explain why template declarations and definitions are usually kept together in the header file.
  • Q: What is the difference between Macros (#define) and Templates for generic programming? (Answer: Templates are type-safe and evaluated by the compiler; Macros are blind text-replacements evaluated by the preprocessor).
  • Q: What is Template Metaprogramming?

13. Summary

Templates enable Generic Programming, allowing you to write a function or class once and use it with any data type. The compiler handles generating the specific versions behind the scenes. This is the exact mechanism used to build C++'s Standard Template Library (STL).

14. Next Chapter Recommendation

Before we dive into the STL, we need to know how to handle errors safely. In Chapter 21: Exception Handling, we will learn how to use try, catch, and throw.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·