Class Templates – Generic Classes in C++
Posted by Andrew Myhre on January 20, 2008
Since C# 2.0 we’ve been able to use the following syntax:
82 public class MyClass<t>
83 {
84 private t obj;
85 public MyClass(t theObject)
86 {
87 this.obj = theObject;
88 }
89
90 public t doit()
91 {
92 return obj;
93 }
94 }
This can be accomplished in C++ in the following way:
1 template <class T>
2 class MyClass
3 {
4 public:
5 MyClass(T* obj) ;
6 ~MyClass();
7 T* doit();
8 private:
9 T* theObject;
10 } ;
11
12 MyClass::MyClass(T *obj)
13 {
14 theObject = obj;
15 }
16
17 T* MyClass::doit()
18 {
19 return theObject;
20 }
This is how we can implement strongly-typed object managers, as well as smart pointers.