[UCR]  
[/\]
Universidad de Costa Rica
Escuela de Ciencias de la
Computación e Informática
[<=] [home] [<>] [\/] [=>]

The Tdef.h trick to teach C++ templates

Adolfo Di Mare



 

Abstract [<>] [\/] [/\]

Presentamos una técnica sencilla que facilita la enseñanza de plantillas para el lenguaje C++. We discuss a simple technique to facilitate teaching C++ templates.
int main() {
    Stack_int S;
    int d = -1;

    S.Push(1);    // 1
    S.Push(2);    // 1 2
    S.Push(3);    // 1 2 3
    S.Push(4);    // 1 2 3 4
    S.Push(5);    // 1 2 3 4 5

    d = S.Pop(); // 1 2 3 4    [5]
    d = S.Count();   // 4





    S.Push(6);    // 1 2 3 4 6
    d = S.Count();   // 5
    S.Push(7);    // 1 2 3 4 6 7
    d = S.Count();   // 6

    d = S.Pop(); // 1 2 3 4 6  [7]
    d = S.Count();   // 5

    return 0;
} // main()
Figure 1

      Generic programming is a concept that has been developed for more than 20 years. It has always been difficult to teach, for it requires the apprentice to master basic concepts of abstraction for algorithms and data abstraction. This forces instructors to introduce these concepts in an advanced course. Since templates are "text editor polymorphism" [MDC-91], it is possible to cover them early, with simplicity and precision, based on C++ "macros". Figure 1 is a simple program that can be used to introduce the concept of container as an object used to store to other objects.

int main() {
    Stack_int S;
    // ...
} // main()
class Stack_int {
public:
    Stack_int()      { m_top = 0; return; }
    void Push(int d) { m_vec[m_top] = d; m_top++; return; }
    int  Pop()       { m_top--; return m_vec[m_top]; }
    int  Top()       { return m_vec[m_top-1]; }
    int  Count()     { return m_top; }
private:
    enum { Capacity = 132 };
    int  m_top;           // stack's top
    int  m_vec[Capacity]; // stack's array of values
}; // Stack_int
Figure 2: tStack2.cpp

      It is easy for students to understand that a vector can be used to implement the stack operations; the implementation at the bottom of Figure 2 is familiar to them.

int main() {
    Stack_T S;
    // ...
} // main()
typedef int T;

class Stack_T {
public:
    Stack_T()      { m_top = 0; return; }
    void Push(T d) { m_vec[m_top] = d; m_top++; return; }
    T    Pop()     { m_top--; return m_vec[m_top]; }
    T    Top()     { return m_vec[m_top-1]; }
    int  Count()   { return m_top; }
private:
    enum { Capacity = 132 };
    int  m_top;           // stack's top
    T    m_vec[Capacity]; // stack's array of values
}; // Stack_T
Figure 3: tStack3.cpp

      Figure 3 shows the result of making small changes with the text editor to obtain class "Stack_T", which has the same functionality as class "Stack_int" from Figure 2. It is simple for students to understand the advantages of a more general class when they realize that changing a single line of code can result in a generic class:
      "typedef int T;"

// Tdef.h

#ifndef Tdef_h
    #define Tdef_h
    typedef  int T;
#endif // Tdef_h
// Tdef.h

#ifndef Tdef_h
    #define Tdef_h
    #define T int
#endif // Tdef_h
#ifndef Tdef_h
    #include "Tdef.h"
#endif // Tdef_h

class Stack_T {
public:
    Stack_T()      { m_top = 0; return; }
    void Push(T d) { m_vec[m_top] = d; m_top++; return; }
    T    Pop()     { m_top--; return m_vec[m_top]; }
    T    Top()     { return m_vec[m_top-1]; }
    int  Count()   { return m_top; }
private:
    enum { Capacity = 132 };
    int  m_top;           // stack's top
    T    m_vec[Capacity]; // stack's array of values
}; // Stack_T
Figure 4: tStack4.cpp

      The "Tdef.h" trick is to put the line where the data type stored in the stack is defined in a header file called "Tdef.h". The main program remains the same as the one on Figure 2. At the beginning of Figure 4 there are 2 versions for "Tdef.h" which can be used to parametrize the stack. It is possible to explain how macros and the C++ preprocessor work while explaining the necessity to use the conditional compilation directives "#ifndef".

int main() {
    Stack<int> S;
    // ...
} // main()
template <class T>
class Stack {
public:
    Stack()        { m_top = 0; return; }
    void Push(T d) { m_vec[m_top] = d; m_top++; return; }
    T    Pop()     { m_top--; return m_vec[m_top]; }
    T    Top()     { return m_vec[m_top-1]; }
    int  Count()   { return m_top; }
private:
    enum { Capacity = 132 };
    int  m_top;           // stack's top
    T    m_vec[Capacity]; // stack's array of values
}; // Stack
Figure 5: tStackT.cpp

      After having a generic class it is relatively simple to transform it into a template class, like the one in Figure 5. Many students choose to use the "Tdef.h" class without templates. They do so because while coding the compiler shows errors that are easier to understand than those of a template class, in spite of the limitation that only one data type can be used for the container.

      Using this pedagogic approach achieves very good results, for it takes about 2 hours to introduce templates after explaining the C++ preprocessor and its "macros". Since students understand how the text substitution mechanism for templates works, they can write an debug generic programs with little effort, because they first build the "Tdef.h" version and later "templatetize" it when it is debugged.

 

Conclusion [<>] [\/] [/\]

      The "Tdef.h" trick has several important advantages:

 

Acknowledgements [<>] [\/] [/\]

      Miguel Angel Prieto, Manuel Enrique Bermúdez and Alejandro Di Mare contributed with several observations and important suggestions to improve this work.

 

References [<>] [\/] [/\]


           

[AHU-84] Aho, Alfred V.; Hopcroft, John E.; Ullman, Jefrrey D.: Data Structures and Algorithms, Addisson Wesley Publishing Co., 1984.
[Low-2003] Lowy, Juval: An Introduction to C# Generics, Microsoft MSDN Library; August 2003.
      http://msdn.microsoft.com/library/en-us/dnvs05/html/csharp_generics.asp
[MDC-91] Morrison, P. & Dearle, A. & Connor, R. C. H. & Brown, A. L.: An Ad Hoc Approach to the Implementation of Polymorphism, ACM Transactions on Programming Languages and Systems, Vol.13 No.3, pp [342-371], Julio 1991.
      http://www.dcs.st-and.ac.uk/research/publications/download/MDC+91.pdf
[Str-98] Stroustrup, Bjarne: The C++ Programming Language, 3rd edition, ISBN 0-201-88954-4; Addison-Wesley, 1998.
      http://www.research.att.com/~bs/papers.html

 

Index [<>] [\/] [/\]

[-] Abstract
[-] Conclusion
[-] Acknowledgements

References
Index
About the author
About this document
[/\] Beginning [<>] Index [\/] End

 

About the author [<>] [\/] [/\]

Adolfo Di Mare: Costarrican Researcher at the Escuela de Ciencias de la Computación e Informática [ECCI], Universidad de Costa Rica [UCR], where he is full professor. Works on Internet and programming technologies. He is Tutor at the Stvdivm Generale in the Universidad Autónoma de Centro América [UACA], where he is Cathedraticum. Obtained the Licenciatura at UCR, and the Master of Science in Computer Science from the University of California, Los Angeles [UCLA], and the Ph.D. at the Universidad Autónoma de Centro América.
Adolfo Di Mare: Investigador costarricense en la Escuela de Ciencias de la Computación e Informática [ECCI] de la Universidad de Costa Rica [UCR], en donde ostenta el rango de Profesor Catedrático. Trabaja en las tecnologías de Programación e Internet. Es Maestro Tutor del Stvdivm Generale de la Universidad Autónoma de Centro América [UACA], en donde ostenta el rango de Catedrático. Obtuvo la Licenciatura en la Universidad de Costa Rica, la Maestría en Ciencias en la Universidad de California, Los Angeles [UCLA], y el Doctorado (Ph.D.) en la Universidad Autónoma de Centro América.
[mailto]Adolfo Di Mare <adolfo@di-mare.com>

 

About this document [<>] [\/] [/\]

Reference: Di Mare, Adolfo: The Tdef.h trick to teach C++ templates , Reporte Técnico ECCI-2004-01(en), Escuela de Ciencias de la Computación e Informática, Universidad de Costa Rica, 2004.
Internet: http://www.di-mare.com/adolfo/p/tdefen.htm
Author: Adolfo Di Mare <adolfo@di-mare.com>
Contact: Apdo 4249-1000, San José Costa Rica
Tel: (506) 207-4020       Fax: (506) 438-0139
Revision: ECCI-UCR, Octubre 2004
Visitors:


Copyright © 2004 Adolfo Di Mare
Derechos de autor reservados © 2004 Adolfo Di Mare <adolfo@di-mare.com>
[home] [<>] [/\]