C++ Function Templates

Function Templates in C++

Function templates in C++ enable you to create generic functions that can work with multiple data types. A template is a blueprint for generating functions with specific data types at compile-time based on the types of arguments passed during a function call.

In this tutorial, we'll cover the basics of function templates in C++.

  • Include the required headers: To use the iostream library, include the iostream header.
#include <iostream> 
  • Defining a Function Template:

To define a function template, use the template keyword followed by the template parameter list in angle brackets <>. The template parameter list typically contains one or more type parameters, each preceded by the typename keyword (or the class keyword).

Example:

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

In this example, we define a template function findMax that takes two parameters of the same type T and returns the maximum of the two.

  • Calling a Function Template:

When calling a function template, the compiler automatically deduces the appropriate data type(s) based on the arguments passed. However, you can also explicitly specify the type by using the function name followed by the type in angle brackets <>.

Example:

#include <iostream> template <typename T> T findMax(T a, T b) { return (a > b) ? a : b; } int main() { int a = 5; int b = 10; double c = 3.5; double d = 7.2; std::cout << "Max of a and b: " << findMax(a, b) << std::endl; std::cout << "Max of c and d: " << findMax(c, d) << std::endl; std::cout << "Max of a and c: " << findMax<int>(a, static_cast<int>(c)) << std::endl; return 0; } 

Output:

Max of a and b: 10 Max of c and d: 7.2 Max of a and c: 5 

In this example, the findMax function is called with different data types. The compiler generates appropriate functions for each data type combination. When the data types of the arguments don't match, you can explicitly specify the type and use casting as needed.

Function templates enable you to write generic code that can work with multiple data types, improving code reusability and reducing the need for duplicate code.

Examples

  1. How to use function templates in C++:

    • Description: Introduces the concept of function templates, which allow writing generic functions that can operate on multiple data types.
    • Example Code:
      #include <iostream> // Function template template <typename T> T add(T a, T b) { return a + b; } int main() { std::cout << add(1, 2) << std::endl; // Calls the template with int std::cout << add(1.5, 2.5) << std::endl; // Calls the template with double return 0; } 
  2. Template specialization for functions in C++:

    • Description: Explores template specialization, allowing custom implementations for specific data types.
    • Example Code:
      #include <iostream> // Generic template template <typename T> void display(T value) { std::cout << "Generic display: " << value << std::endl; } // Template specialization for int template <> void display<int>(int value) { std::cout << "Specialized display for int: " << value << std::endl; } int main() { display(42); // Calls the specialized version for int display(3.14); // Calls the generic version return 0; } 
  3. Template functions with multiple parameters in C++:

    • Description: Extends function templates to handle multiple template parameters.
    • Example Code:
      #include <iostream> // Function template with multiple parameters template <typename T, typename U> T multiply(T a, U b) { return a * b; } int main() { std::cout << multiply(2, 3.5) << std::endl; // Calls the template with int and double return 0; } 
  4. Function template constraints in C++:

    • Description: Introduces template constraints to restrict the types of arguments that can be used with a template.
    • Example Code:
      #include <iostream> #include <type_traits> // Function template with constraint template <typename T, typename U> std::enable_if_t<std::is_integral<T>::value && std::is_integral<U>::value, T> addIntegrals(T a, U b) { return a + b; } int main() { std::cout << addIntegrals(2, 3) << std::endl; // Calls the template with int // std::cout << addIntegrals(2.5, 3) << std::endl; // Compilation error (double not allowed) return 0; } 
  5. C++ template specialization for function templates:

    • Description: Applies template specialization to entire function templates, allowing custom implementations for specific types.
    • Example Code:
      #include <iostream> // Generic template template <typename T> void display(T value) { std::cout << "Generic display: " << value << std::endl; } // Template specialization for char* template <> void display<char*>(char* value) { std::cout << "Specialized display for char*: " << value << std::endl; } int main() { display(42); // Calls the generic version display("Hello, World!"); // Calls the specialized version for char* return 0; } 
  6. Template functions and type deduction in C++:

    • Description: Explains how C++ template functions use type deduction to automatically determine template arguments.
    • Example Code:
      #include <iostream> // Function template with type deduction template <typename T> T add(T a, T b) { return a + b; } int main() { std::cout << add(1, 2) << std::endl; // Type deduction: int std::cout << add(1.5, 2.5) << std::endl; // Type deduction: double return 0; } 
  7. Variadic function templates in C++:

    • Description: Introduces variadic function templates, allowing functions with a variable number of arguments.
    • Example Code:
      #include <iostream> // Variadic function template template <typename... Args> void displayArgs(Args... args) { (std::cout << ... << args) << std::endl; } int main() { displayArgs(1, 2, 3, "Hello"); // Calls the template with multiple arguments return 0; } 
  8. Function template overloading in C++:

    • Description: Shows how function templates can be overloaded to provide specific implementations for different cases.
    • Example Code:
      #include <iostream> // Function template overloading template <typename T> void display(T value) { std::cout << "Generic display: " << value << std::endl; } // Overloaded template for strings template <> void display<std::string>(std::string value) { std::cout << "Specialized display for string: " << value << std::endl; } int main() { display(42); // Calls the generic version display("Hello, World!"); // Calls the specialized version for string return 0; } 
  9. Examples of function templates for containers in C++:

    • Description: Provides examples of using function templates with containers, showcasing generic algorithms.
    • Example Code:
      #include <iostream> #include <vector> // Function template for printing container elements template <typename Container> void printContainer(const Container& container) { for (const auto& element : container) { std::cout << element << " "; } std::cout << std::endl; } int main() { std::vector<int> numbers = {1, 2, 3, 4, 5}; printContainer(numbers); // Calls the template with vector<int> return 0; } 

More Tags

fusedlocationproviderapi shopping-cart expression-trees eonasdan-datetimepicker local-files nonblocking pocketpc java-stream amazon-sqs windows-server-2012

More Programming Guides

Other Guides

More Programming Examples