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); // Implicit template parameter deduction double f = 5.5; double g = 42.0; swap(f, g); printf("f=%f, g=%f\n", f, g); } /* Output: a=42, b=6 f=42.0, g=5.5 */
funnction template
// function template #include <iostream> using namespace std; template <class F> F sum (T a, T b) { F add; add = a + b; return result; } int main () { int i=5, j=6, s1; double a=3.6, b=5.5, s2; s1=sum<int>(i,j); s2=sum<double>(a,b); cout << s1 << endl; cout << s2 << endl; return 0; }
Source: cplusplus.com