1template <class T>
2void swap(T & lhs, T & rhs)
3{
4 T tmp = lhs;
5 lhs = rhs;
6 rhs = tmp;
7}
1template <class T>
2void swap(T & lhs, T & rhs)
3{
4 T tmp = lhs;
5 lhs = rhs;
6 rhs = tmp;
7}
8
9void main()
10{
11 int a = 6;
12 int b = 42;
13 swap<int>(a, b);
14 printf("a=%d, b=%d\n", a, b);
15
16 // Implicit template parameter deduction
17 double f = 5.5;
18 double g = 42.0;
19 swap(f, g);
20 printf("f=%f, g=%f\n", f, g);
21}
22
23/*
24Output:
25a=42, b=6
26f=42.0, g=5.5
27*/
1// function template
2#include <iostream>
3using namespace std;
4
5template <class T>
6T GetMax (T a, T b) {
7 T result;
8 result = (a>b)? a : b;
9 return (result);
10}
11
12int main () {
13 int i=5, j=6, k;
14 long l=10, m=5, n;
15 k=GetMax<int>(i,j);
16 n=GetMax<long>(l,m);
17 cout << k << endl;
18 cout << n << endl;
19 return 0;
20}
1#include <vector>
2
3// This is your own template
4// T it's just a type
5template <class T1, class T2, typename T3, typename T4 = int>
6class MyClass
7{
8 public:
9 MyClass() { }
10
11 private:
12 T1 data; // For example this data variable is T type
13 T2 anotherData; // Actually you can name it as you wish but
14 T3 variable; // for convenience you should name it T
15}
16
17int main(int argc, char **argv)
18{
19 std::vector<int> array(10);
20 // ^^^
21 // This is a template in std library
22
23 MyClass<int> object();
24 // This is how it works with your class, just a template for type
25 // < > angle brackets means "choose" any type you want
26 // But it isn't necessary should work, because of some reasons
27 // For example you need a type that do not supporting with class
28 return (0);
29}
1template <class myType>
2myType GetMax (myType a, myType b) {
3 return (a>b?a:b);
4}