Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Templates

What are Templates?

Templates are powerful tools in programming that allow for the creation of functions and classes that operate with generic types. This enables code reuse and type safety. Templates are particularly useful in scenarios where you want to write a function or a class that can work with any data type.

Function Templates

A function template defines a pattern for a function that can operate on different data types. Here’s how you define a simple function template in C++:

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

In the example above, <typename T> tells the compiler that T is a placeholder for a data type. The function add can now be used with any data type that supports the + operator:

int main() {
  cout << add(5, 3) << endl; // Outputs: 8
  cout << add(2.5, 3.1) << endl; // Outputs: 5.6
  return 0;
}

Class Templates

Class templates follow a similar concept but apply to classes. They allow you to create a class that can handle any data type:

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

Here, the class Box is defined with a template parameter T. This allows instances of Box to be created with different data types:

int main() {
  Box<int> intBox(123);
  Box<string> strBox("Hello");
  cout << intBox.getValue() << endl; // Outputs: 123
  cout << strBox.getValue() << endl; // Outputs: Hello
  return 0;
}

Template Specialization

Sometimes you may need to handle a specific data type differently from the generic implementation. This is where template specialization comes in:

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

// Specialization for type char
template <>
class Box<char> {
  private:
    char value;
  public:
    Box(char val) : value(val) {}
    char getValue() { return value; }
    void show() { cout << "Character: " << value << endl; }
};

In the example above, a specialized version of the Box class is provided for the char type. This specialized class includes an additional method show to display the character:

int main() {
  Box<char> charBox('A');
  charBox.show(); // Outputs: Character: A
  return 0;
}

Conclusion

Templates are an essential part of modern C++ programming. They provide tremendous flexibility and reusability by allowing you to write generic and type-safe code. Understanding templates is crucial for writing efficient and maintainable code in C++.