Lesson 9
Templates
Write generic, reusable code
1What are Templates?✨
Templates in C++ allow you to write generic and reusable code. They enable you to create functions and classes that can work with any data type, making your code more flexible and efficient!
2Why Use Templates?🎯
- ✓ Reduce code duplication
- ✓ Increase code reusability
- ✓ Enhance type safety
- ✓ Simplify maintenance of code
3Creating a Function Template💡
You can create a function template to perform operations on different data types. Here’s a simple example of a function that swaps two values:
4template<typename T>🚀
void swap(T &a, T &b) {
T temp = a;
a = b;
b = temp;
}This function can swap integers, floats, or any other data type!
5Creating a Class Template🔍
Just like functions, you can create class templates. Here’s how to create a simple class for a Pair:
6template<typename T1, typename T2>⭐
class Pair {
public:
T1 first;
T2 second; Pair(T1 f, T2 s) : first(f), second(s) {} void display() {
std::cout << "First: " << first << ", Second: " << second << std::endl;
}
};This Pair class can hold two values of different types!
7Using Templates🧩
To use your templates, simply declare them with specific data types:
int main() {
int x = 10, y = 20;
swap(x, y); Pair<int, double> myPair(1, 2.5);
myPair.display(); return 0;
}8What You'll Build This Grade🎈
- ✓ Generic functions for sorting and searching
- ✓ Template-based data structures like stacks and queues
- ✓ Complex applications with reusable components
- ✓ Enhanced understanding of type safety in coding
🎯 Practice Challenges
Master Templates by completing all 3 difficulty levels
Templates - Easy Challenge
Start with the basics. Perfect for beginners!
Templates - Medium Challenge
Get more challenging. Build your confidence!
Templates - Hard Challenge
Master this concept. Prove your skills!
🏆 Study a lesson for 2+ minutes to earn +10 TalentJR Points a day. Badges, certificates & prizes →
Ready to Master Templates? 🚀
Complete the challenges, take the quiz and keep your learning streak going!
Keep learning
- ← Previous lessonLesson 8: Operator OverloadingMake custom types feel built-in
- Next lesson →Lesson 10: Exception Handling in C++try, catch, and throw
- Grade 12 courseDatabases - Data Management MasterSQL coding course for kids.
- Student ToolsFree calculators for studentsPercentage, fraction, ratio and marks calculators with steps.
- CBSEClass 11 CBSE & NCERT study materialMaths, Science and Computer chapters with solutions.
- Future SkillsExplore future skillsAI, robotics and new-age skills explained for students.