Templates in C++ are a powerful feature that allows you to write generic and reusable code. They enable functions and classes to operate with generic types, which means you can create a function or a class to work with any data type without rewriting the code for each type.

Key Concepts

  1. Function Templates: Allow functions to operate with generic types.
  2. Class Templates: Allow classes to operate with generic types.
  3. Template Specialization: Allows you to define a specific implementation of a template for a particular type.

Function Templates

Function templates allow you to create a single function definition that works with different data types. Here's a basic example:

#include <iostream>
using namespace std;

// Function template
template <typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    cout << "Int: " << add(1, 2) << endl;         // Works with integers
    cout << "Double: " << add(1.1, 2.2) << endl;  // Works with doubles
    return 0;
}

Explanation

  • template <typename T>: This line declares a template. T is a placeholder for a data type.
  • T add(T a, T b): This is a function template that can take any type T and return a value of type T.
  • The main function demonstrates how the add function can be used with different data types.

Class Templates

Class templates allow you to create a class that can handle any data type. Here's an example:

#include <iostream>
using namespace std;

// Class template
template <typename T>
class Box {
private:
    T value;
public:
    Box(T v) : value(v) {}
    T getValue() {
        return value;
    }
};

int main() {
    Box<int> intBox(123);          // Box for integers
    Box<double> doubleBox(123.45); // Box for doubles

    cout << "Int Box: " << intBox.getValue() << endl;
    cout << "Double Box: " << doubleBox.getValue() << endl;
    return 0;
}

Explanation

  • template <typename T>: This line declares a template for the class.
  • class Box { ... }: This is a class template that can handle any type T.
  • The main function demonstrates how the Box class can be used with different data types.

Template Specialization

Template specialization allows you to define a specific implementation of a template for a particular type. Here's an example:

#include <iostream>
using namespace std;

// Generic template
template <typename T>
class Box {
public:
    T value;
    Box(T v) : value(v) {}
    void print() {
        cout << "Generic Box: " << value << endl;
    }
};

// Template specialization for char*
template <>
class Box<char*> {
public:
    char* value;
    Box(char* v) : value(v) {}
    void print() {
        cout << "Specialized Box: " << value << endl;
    }
};

int main() {
    Box<int> intBox(123);
    Box<char*> charBox("Hello");

    intBox.print();
    charBox.print();
    return 0;
}

Explanation

  • template <typename T>: This line declares a generic template.
  • template <> class Box<char*> { ... }: This line declares a specialized template for char*.
  • The main function demonstrates how the specialized template works differently from the generic template.

Practical Exercises

Exercise 1: Function Template

Create a function template maxValue that returns the maximum of two values.

#include <iostream>
using namespace std;

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

int main() {
    cout << "Max of 3 and 7: " << maxValue(3, 7) << endl;
    cout << "Max of 3.5 and 2.1: " << maxValue(3.5, 2.1) << endl;
    return 0;
}

Solution

  • The maxValue function template compares two values and returns the larger one.
  • The main function demonstrates how the maxValue function can be used with different data types.

Exercise 2: Class Template

Create a class template Pair that holds two values of any type and provides a method to display them.

#include <iostream>
using namespace std;

template <typename T1, typename T2>
class Pair {
private:
    T1 first;
    T2 second;
public:
    Pair(T1 f, T2 s) : first(f), second(s) {}
    void display() {
        cout << "First: " << first << ", Second: " << second << endl;
    }
};

int main() {
    Pair<int, double> p1(1, 1.1);
    Pair<string, char> p2("Hello", 'A');

    p1.display();
    p2.display();
    return 0;
}

Solution

  • The Pair class template holds two values of any type.
  • The display method prints the values.
  • The main function demonstrates how the Pair class can be used with different data types.

Common Mistakes and Tips

  • Type Mismatch: Ensure that the types used with templates are compatible with the operations performed inside the template.
  • Template Syntax: Pay attention to the syntax when declaring and using templates. Missing template keyword or incorrect placement of angle brackets can lead to compilation errors.
  • Specialization: Use template specialization carefully to avoid unexpected behavior.

Conclusion

Templates are a powerful feature in C++ that allow you to write generic and reusable code. By understanding function templates, class templates, and template specialization, you can create flexible and efficient programs. Practice with the provided exercises to reinforce your understanding and prepare for more advanced topics in C++.

© Copyright 2024. All rights reserved