TalentJR

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>🚀

💻 code
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>⭐

💻 code
class Pair {
public:
    T1 first;
    T2 second;
💻 code
    Pair(T1 f, T2 s) : first(f), second(s) {}
💻 code
    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:

💻 code
int main() {
    int x = 10, y = 20;
    swap(x, y);
💻 code
    Pair<int, double> myPair(1, 2.5);
    myPair.display();
💻 code
    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

🟢 EASY

Templates - Easy Challenge

Start with the basics. Perfect for beginners!

🟡 MEDIUM

Templates - Medium Challenge

Get more challenging. Build your confidence!

🔴 HARD

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!