Templates

Let's start with something really simple. Here is a function that can receive 3 arguments of the same type and print them out.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<string>
using namespace std;
template <class T>
void show3(T a,T b,T c) {
  cout<<a<<","<<b<<","<<c<<endl;
} //show3

int main() {
  show3(35,17,20);
  show3("Peter","Paul","Mary");
  show3(2.5,12.6,2.0);
  system("pause");
  return 0;
}//main
CODE
35,17,20
Peter,Paul,Mary
2.5,12.6,2
Press any key to continue . . .

When we call show3 with 3 integers as the arguments, T (the type) is int. When we pass 3 strings as the arguments, T is string. However, we cannot use this function with mixed types.

NEXT: A Template function to sort 3 values