Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Function Templates in C++

Introduction

Function templates are a powerful feature in C++ that allow you to write generic and reusable functions. By using function templates, you can create functions that work with any data type, thereby reducing code duplication and improving maintainability.

What is a Function Template?

A function template defines a blueprint for generating functions. Unlike regular functions, function templates are not compiled directly. Instead, they are instantiated with specific types when they are called.

Syntax of Function Templates

The basic syntax for defining a function template is as follows:

template <typename T>
return_type function_name(parameters) {
// function body
}

Here, <typename T> is the template parameter list, where T is a placeholder for a data type that will be specified when the function is called.

Example: Function Template for Finding Maximum

Let's create a simple function template to find the maximum of two values.

#include <iostream>
using namespace std;

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

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

Template Specialization

Sometimes you may need to handle specific types differently. This can be achieved using template specialization. Here's an example of how to specialize the findMax function for char* types.

#include <iostream>
#include <cstring>
using namespace std;

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

// Specialization for char*
template <>
const char* findMax(const char* a, const char* b) {
return (strcmp(a, b) > 0) ? a : b;
}

int main() {
cout << "Max of 'apple' and 'banana': " << findMax("apple", "banana") << endl;
return 0;
}
Output:
Max of 'apple' and 'banana': banana

Benefits of Using Function Templates

Function templates provide several benefits:

  • Code Reusability: Write once, use with any data type.
  • Type Safety: Type checking is performed during compilation.
  • Maintainability: Easier to manage and update code.

Conclusion

Function templates are a versatile feature in C++ that enable you to write generic and reusable functions. By understanding and utilizing function templates, you can significantly improve the efficiency and maintainability of your code.