C++ Template Example

Templates can be viewed as a form of static compile time virtualization. Was that a mouthful or what?!? Here is a template example that highlights template specialization and default template parameters that can be over-riden by a class. Remember to always have your template definitions AND implementations in the one cpp file. Do not have a seperate header file for the definitions and a seperate file for the implementation as is customary.

Let us take a look at the example. I strongly suggest you copy this code and compile it and run it on your desktop for a better understanding.

 1. #include <stdio.h>
 2. 
 3. class deer{
 4. public:
 5.     char* getWhat(){return (char*)"I'm a deer";}
 6. };
 7. 
 8. class hog{
 9. public:
10.     char* getWhat(){return (char*)"I'm a hog";}
11. };
12. 
13. class buffalo{
14. public:
15.     char* getWhat(){return (char*)"I'm a buffalo";}
16. };
17. 
18. class man{
19. public:
20.     char* getWhat(){return (char*)"I'm a man - dear god";}
21. };
22. 
23. /*Default digestive classes*/
24. template <typename T>
25. class crocdigest{
26. public:
27.     void digest(T& t){
28.         printf("default template digest %s\n", t.getWhat());
29.     }
30. };
31. 
32. /*Special digestive class*/
33. template <typename T>
34. class special_crocdigest{
35. public:
36.     void digest(T& t){
37.         printf("special class digest %s\n", t.getWhat());
38.     }
39. };
40. 
41. 
42. /*Default croc's meals*/
43. template <class T, class c_crocdigest = crocdigest<T> >
44. class crocsmeal{
45.     c_crocdigest crocdig;
46. public:
47.     int gobble(T&);
48. };
49. template <typename T, class c_crocdigest> 
50. int crocsmeal<T,c_crocdigest>::gobble(T& t){
51.   crocdig.digest(t);
52.   return 0;
53. }
54. 
55. /*specialized template for hogs meal*/
56. template <>
57. class crocsmeal<hog>{
58.   public:
59.     int gobble(const hog& t){
60.       printf("template specialization gobbling the hog\n");
61.       return 0;    
62.     }
63. };
64. 
65. 
66. int main(){
67. 
68.   hog        h;
69.   deer        d;
70.   man        m;
71.   buffalo    b;
72.   
73.   crocsmeal<deer> mealdeer;
74.   crocsmeal<hog> mealhog;
75.   crocsmeal<buffalo> mealbuffalo;
76.   crocsmeal<man, special_crocdigest<man>> mealman;
77.   
78.   mealhog.gobble(h);
79.   mealdeer.gobble(d);
80.   mealbuffalo.gobble(b);
81.   mealman.gobble(m);
82. }
Hide line numbers