-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTemplates.cpp
More file actions
100 lines (73 loc) · 1.48 KB
/
Templates.cpp
File metadata and controls
100 lines (73 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include "stdafx.h"
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
template<class /* OR typename*/ T> T add(T a, T b)
{
return a + b;
}
template <class T> class A
{
public:
A(T t):m_t(t) {}
void function(T t);
private:
T m_t;
};
template < class T> class B
{
public:
B(T* p_t):m_t(p_t) {}
private:
T* m_t;
};
// Templates can also be parameterized by a value parameter
template<int i> class D
{
public:
D() { memset(array, 0, i* sizeof(int)); }
private:
int array[i];
};
// Template with parameter T and non-type template parameter i
template< class T, int i> class TestClass
{
public:
char Buffer[i];
T testFunction(T* p_t);
};
template< class T, int i>
T TestClass<T, i>::testFunction(T* p_t)
{
return *(p_t++);
}
// Use array in template
template<class T> double getAverage(T tArrary[], int i)
{
T tSum = T(); // Initializing to 0;
for(int j = 0; j < i; j++)
tSum += tArrary[j];
return (double) tSum / i;
}
void testTemplates()
{
// 2 types of templates
// 1. Function template
// 2. Class template
// 1. Function template
double dOut = add(23.25, 56.55);
int nOut = add(433, 343);
// 2. Class template
A<int> a(12);
A<double> d(44.44);
int temp = 33;
B<int> c(&temp);
A<int*> m(&temp);
D<22> obj;
TestClass<double, 4> obj5;
int inArrary[4] = { 3, 55, 65, 66 };
double dArray[5] = { 44, 55, 55, 33, 44};
double avg = getAverage(inArrary, 4);
avg = getAverage(dArray, 5);
}