0
0
CppHow-ToBeginner · 4 min read

How to Create Function Template in C++: Syntax and Examples

In C++, you create a function template using the template<typename T> keyword before the function definition. This allows the function to work with any data type specified when called, making your code reusable and flexible.
📐

Syntax

A function template starts with the template<typename T> declaration, where T is a placeholder for a data type. The function uses T as a type in its parameters and return type. When you call the function, the compiler generates the correct version for the type you use.

  • template<typename T>: Declares a template with a type parameter T.
  • ReturnType functionName(T parameter): Defines the function using the template type T.
cpp
template<typename T>
T functionName(T parameter) {
    // function body
    return parameter;
}
💻

Example

This example shows a function template named getMax that returns the larger of two values. It works for any type that supports the > operator, like int or double.

cpp
#include <iostream>

// Function template to find maximum of two values
template<typename T>
T getMax(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    std::cout << getMax(10, 20) << "\n";       // Works with int
    std::cout << getMax(15.5, 9.3) << "\n";    // Works with double
    return 0;
}
Output
20 15.5
⚠️

Common Pitfalls

Common mistakes when creating function templates include:

  • Forgetting the template<typename T> line before the function.
  • Using types inside the function that do not support the operations used (like > without overload).
  • Trying to mix different types without specifying template parameters explicitly.

Here is an example of a wrong and right way:

cpp
// Wrong: Missing template declaration
// int getMax(int a, int b) {
//     return (a > b) ? a : b;
// }

// Right: Template with typename T
template<typename T>
T getMax(T a, T b) {
    return (a > b) ? a : b;
}
📊

Quick Reference

Remember these tips when using function templates:

  • Use template<typename T> before the function.
  • The template type T can be any valid C++ type.
  • Functions must use operations supported by the type T.
  • Templates help avoid code duplication for similar functions.

Key Takeaways

Start a function template with template to make it generic.
Use the template type T in function parameters and return type.
Ensure the operations inside the function are valid for the template type.
Function templates allow writing one function for many data types.
Always include the template declaration before the function definition.