Templates in C++
# CHAPTER 20
Templates in C++
1. Introduction
If you want to write a function that finds the maximum of two integers, you writeint 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 thetemplate keyword.
4. Function Templates
A function template tells the compiler how to generate a function for *any* data type.Syntax: template <typename T>
5. Multiple Template Parameters
Templates can have more than one generic type.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.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.8. Memory-Level Explanation
Templates are NOT code. They are blueprints for code. If you write a template but never use it inmain(), 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
.cppfiles: Because the compiler needs to generate the code at the exact moment the template is called inmain(), template *definitions* must usually be placed entirely in the.hheader file.
-
Forgetting
<Type>in Class Templates: You cannot writeBox b;. You MUST specify the type:Box<int> b;.
10. Exercises
-
1.
Write a function template
swapDatathat swaps two variables of any type. Test it with integers and strings.
-
2.
Write a class template
Pairthat holds two variables of the same generic type, with a methodgetLarger()that returns the larger of the two.
11. MCQ Quiz with Answers
What is the main benefit of templates?
Which keyword is used to declare a template parameter?
If a template is never called, how much compiled machine code is generated for it?
What is Template Instantiation?
<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>)
What is Template Specialization?
Where should template definitions typically be placed?
What is a potential downside of heavy template usage?
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 usetry, catch, and throw.