how to use function in template code example
Example 1: function template
template <class T>
void swap(T & lhs, T & rhs)
{
T tmp = lhs;
lhs = rhs;
rhs = tmp;
}
void main()
{
int a = 6;
int b = 42;
swap<int>(a, b);
printf("a=%d, b=%d\n", a, b);
double f = 5.5;
double g = 42.0;
swap(f, g);
printf("f=%f, g=%f\n", f, g);
}
Example 2: Function Template
#include <iostream>
#include <string>
using namespace std;
template <class calculator>
calculator addNumber(calculator A, calculator B) {
return A + B;
}
int main() {
int a = 7, b = 55;
float x = 77.77, y = 8.99;
double u = 4.44, v = 7.88;
string i = "My ", j = "God!";
std::cout << addNumber(a, b) << endl;
std::cout << addNumber(x, y) << endl;
std::cout << addNumber(u, v) << endl;
std::cout << addNumber(i, j) << endl;
}