Function Templates

Generic functions

Interview Relevant: Template basics

Function Templates

Write functions that work with any type.

Code Examples

Function templates for generic programming.

cpp
1// Basic function template
2template<typename T>
3T max(T a, T b) {
4    return (a > b) ? a : b;
5}
6
7// Usage - type deduction
8int m1 = max(3, 5);         // max<int>
9double m2 = max(3.14, 2.71); // max<double>
10int m3 = max<int>(3.5, 2.7); // Explicit type
11
12// Multiple type parameters
13template<typename T, typename U>
14auto add(T a, U b) -> decltype(a + b) {
15    return a + b;
16}
17auto result = add(3, 3.14);  // double
18
19// Non-type template parameter
20template<typename T, int Size>
21class Array {
22    T data[Size];
23};
24Array<int, 10> arr;

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In