-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10_template.cpp
More file actions
64 lines (52 loc) · 1.09 KB
/
10_template.cpp
File metadata and controls
64 lines (52 loc) · 1.09 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
/*
* Templates are used when it is wanted to use the exactly same code
* just with different data type
*
* Template is inicialized by adding template<typename T> infront of function, class...
*/
#include <set>
//template class
template<typename T>
class AnySet {
public:
bool addElement( const T& x){
//insert return a pair<iterator,bool>
return this->mySet.insert( x ).second;
}
bool removeElement( const T& x ){
if ( this->mySet.erase( x ) > 0 )
return true;
else
return false;
}
private:
std::set<T> mySet;
};
//template function
template<typename T>
T compareAnyType( T x, T y ){
return x < y;
};
//template struct
template<typename T>
struct MyStruct
{
T myVar;
};
int main(){
AnySet<int> *i = new AnySet<int>();
i->addElement( 5 );
i->addElement( 10 );
i->removeElement( 10 );
delete i;
AnySet<char> *ch = new AnySet<char>();
ch->addElement( 'a' );
ch->addElement( 'y' );
ch->removeElement( 'a' );
delete ch;
MyStruct<int> s;
s.myVar = 5;
MyStruct<bool> s2;
s.myVar = false;
return 0;
}