Generic Programming Using C++ Templates

W
Document Sample
scope of work template
							Generic Programming Using
     C++ Templates            Generic . . .
                              Using templates




     Brian A. Malloy
Computer Science Department

                                     Slide 1 of 18



                                       Go Back



                                      Full Screen



                                         Quit
1. Generic Programming is “pro-
   gramming with concepts”                          Generic . . .
                                                    Using templates

    • A concept is defined as a family of abstrac-
      tions that are all related by a common set
      of requirements.

    • Major task: identify sets of requirements
      that can be met by a family of abstractions
                                                           Slide 2 of 18
      but are restrictive enough that programs
      can be written that work efficiently with
      all members of the family.                             Go Back


    • STL is an excellent example.                          Full Screen



                                                               Quit
1.1. What problems can be solved by
     Templates?                                        Generic . . .
                                                       Using templates
      • Compiled languages, for example C++, re-
        quire variables, functions and constructs to
        be declared with a certain type.

      • However, a lot of code looks the same de-
        spite the type used!
                                                              Slide 3 of 18
      • Templates solve this problem (1) without
        repeating code, (2) without using void*, (3)
                                                                Go Back
        without using special preprocessors.

                                                               Full Screen



                                                                  Quit
1.2. A Templated language construct is
     a construct with a hole for the type           Generic . . .
                                                    Using templates
    template <typename T>
    inline T const& max(T const& a, T const& b) {
      return a < b ? b : a;
    }
    nt main() {
       std::cout << max(3, 7) << std::endl;
       std::cout << max(3.5, 7.1) << std::endl;            Slide 4 of 18
       return 0;
    }                                                        Go Back



                                                            Full Screen



                                                               Quit
1.3. A generic stack
    1 #include <vector>              Generic . . .

    2 template <typename TYPE>       Using templates
    3 class Stack {
    4 public:
    5   Stack() : _top(-1) {}
    6   TYPE top();
    7   void pop();
    8   void push(TYPE x);
                                            Slide 5 of 18
    10 private:
    11    int _top;
                                              Go Back
    12    enum { MAX = 100 };
    13    enum { EMPTY = -1 };
    14    std::vector<TYPE> items;           Full Screen

    15 };
                                                Quit
1.4. The keyword typename
                                                       Generic . . .
      • Introduces a type parameter
                                                       Using templates
      • Parameters can also be ordinary values of
        constants.

      • Historically, the keyword class was used to
        define a type parameter. Semantically there’s
        no difference between using class and type-
        name; so, to avoid confusion, we use type-            Slide 6 of 18

        name in this context.
                                                                Go Back



                                                               Full Screen



                                                                  Quit
1.5. The typename keyword is sometimes
     needed to distinguish an expression        Generic . . .
     from a declaration                         Using templates

    template <class T>
    inline void PRINT_ELEMENTS(const T &coll,
       const char * optcstr="") {
       typename T::const_iterator pos;
       std::cout << optcstr;
       for (pos = coll.begin();                        Slide 7 of 18
            pos != coll.end(); ++pos) {
          std::cout << *pos << ’ ’;                      Go Back
       }
       std::cout << std::endl;
                                                        Full Screen
    }

                                                           Quit
1.6. Using the Template
                                                   Generic . . .
      • Functions are instantiated automatically
                                                   Using templates
      • Classes must be instantiated by the pro-
        grammer




                                                          Slide 8 of 18



                                                            Go Back



                                                           Full Screen



                                                              Quit
2. Using templates
                                                    Generic . . .
    • In practice, using templates can be differ-    Using templates
      ent from using ordinary code.

    • Templates lie someplace between macros
      and ordinary code.

    • There are several models that are popular
      for including template code into a project.
                                                           Slide 9 of 18



                                                             Go Back



                                                            Full Screen



                                                               Quit
2.1. The Inclusion Model: putting all
     templates in one file                             Generic . . .
                                                      Using templates
    1 #include <iostream>
    2 template <typename T>
    3 void print_typeof(T const& x) {
    4   std::cout << typeid(x).name() << std::endl;
    5 }
    6 int main() {
    7   double ice = 3.0;                                   Slide 10 of 18
    8   print_typeof(ice);
    9   return 0;                                              Go Back
    10}
                                                              Full Screen



                                                                 Quit
2.2. If we separate the declaration, def-
     inition, and use of a template, we             Generic . . .
     will likely get link errors                    Using templates

    ************** typeof.hpp **************
    1 template <typename T>
    2 void print_typeof(T const& );

    ************** typeof.cpp **************
    1 #include <iostream>                                 Slide 11 of 18

    2 #include "typeof.h"
    3 template <typename T>                                  Go Back
    4 void print_typeof(T const& x) {
    5 std::cout << typeid(x).name() << std::endl;           Full Screen
    6 }
                                                               Quit
*************** main.cpp ***************
1 #include "typeof.h"
                                             Generic . . .
2 int main() {
                                             Using templates
3    double ice = 3.0;
4    print_typeof(ice);
5 }

g++ main.cpp typeof.cpp
In function ‘main’:main.cpp:
undefined reference to                             Slide 12 of 18
‘void print_typeof<double>(double const&)’
collect2: ld returned 1 exit status                   Go Back



                                                     Full Screen



                                                        Quit
2.3. Inclusion Model: put everything in
     one file                                   Generic . . .

    *************** main.cpp ***************   Using templates

    1 #include "typeof.cpp"
    2 int main() {
    3    double ice = 3.0;
    4    print_typeof(ice);
    5 }
                                                     Slide 13 of 18
    *************** Result   ***************
    $ g++ main.cpp
                                                        Go Back
    $ a.out
    d
                                                       Full Screen



                                                          Quit
2.4. Inclusion model increases the cost
     of using templates because <iostream>              Generic . . .
     is now included in main                            Using templates


       • <iostream> is a large file that also includes
         templates.

       • The inclusion model will substantially in-
         crease compilation times for large programs.
                                                              Slide 14 of 18
       • Nevertheless, the inclusion model is favored
         over other models, inspite of increase in
                                                                 Go Back
         build time.

                                                                Full Screen



                                                                   Quit
2.5. Explicit Instantiation Model: cre-
     ate an instance for each type that       Generic . . .
     you will need                            Using templates

    1 #include "typeof.h"
    2 template void
      print_typeof<double>(double const& );
    3 int main() {
    4   double ice = 3.0;
    5   print_typeof(ice);                          Slide 15 of 18

    6 }
                                                       Go Back



                                                      Full Screen



                                                         Quit
2.6. Explicit Instantiation Model: you
     can also create an instance for class   Generic . . .
     templates                               Using templates

    template class Stack<int>;




                                                   Slide 16 of 18



                                                      Go Back



                                                     Full Screen



                                                        Quit
2.7. Tradeoffs for Explicit Instantiation
                                                         Generic . . .
       • Manual instantiation has a clear disadvan-
                                                         Using templates
         tage: for large programs the burden of man-
         ual instantiation becomes huge. This bur-
         den is easily underestimated.

       • Advantages of explicit instantiation:

           – The overhead of large headers is avoided.
                                                               Slide 17 of 18
           – Source code for template definitions
             can be kept hidden
                                                                  Go Back
           – for some applications, it can be ad-
             vantageous to control the location of
                                                                 Full Screen
             instantiation.

                                                                    Quit

						
Related docs