example1_simple_function_template.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <iostream>

// Define a function template that adds two values
template<typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    int x = 5, y = 10;
    double a = 2.5, b = 3.7;

    // Call the function template with different types
    std::cout << "Sum of integers: " << add(x, y) << std::endl;
    std::cout << "Sum of doubles: " << add(a, b) << std::endl;

    return 0;
}
Back to templates