object oriented lecture notes

Upload: cjboo2

Post on 03-Apr-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 Object Oriented Lecture Notes

    1/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    COMP3171/COMP9171Object-Oriented Programming

    Lecture 08(Tue)

    Jingling Xue

    CSE, UNSW

    September 11, 2012

    1

  • 7/29/2019 Object Oriented Lecture Notes

    2/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Static vs. Dynamic Polymorphism

    Dynamic (runtime) polymorphism: virtual functions arepolymophic across types related by inheritance

    Static (compile-time) polymorphism:

    Function overloading

    Templates: polymophical across unrelated typesWidely used in libraries (e.g., the STL library) to achievegenerality, flexibility and efficiencySTL containers, iterators and algorithms are templates

    vector vi;

    vector vf;sort(vi.begin(), vi.end))

    sort(vf.begin(), vf.end))

    2

  • 7/29/2019 Object Oriented Lecture Notes

    3/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    What Is Generic Programming (GP)?

    GP is about generalising software components so that they areindependent of any particular type

    Function and class templates are the foundation of GPSTL is an example of generic programming

    Week 8

    Function templates (Tue)Class templates (Thur)

    3

  • 7/29/2019 Object Oriented Lecture Notes

    4/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Example 1

    Read in an arbitrary number of integers (n > 1)from numbers.txt and display:

    Minimum, maximum

    MedianAverageGeometric mean (y1 . . . yn)

    1n

    How many lines would it take you?

    Arbitrary storage (for median), sorting, loops, ...

    4

  • 7/29/2019 Object Oriented Lecture Notes

    5/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Example 1: STL Solution (based on GP)#include

    #include

    #include#include

    #include

    #include

    #include

    #include

    vector v;ifstream in("numbers.txt");

    copy(istream_iterator(in),

    istream_iterator(), back_inserter(v));

    sort(v.begin(), v.end());

    cout

  • 7/29/2019 Object Oriented Lecture Notes

    6/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Example 2Write a program that outputs the words and the number of timesit occurs in a file (sorted by word)

    vector v;

    map m;

    ifstream in("words.txt");

    copy(istream_iterator(in),istream_iterator(), back_inserter(v));

    for (vector::iterator vi = v.begin();

    vi != v.end(); ++vi)

    ++m[*vi];

    for (map::iterator mi = m.begin();

    mi != m.end(); ++mi)

    cout first

  • 7/29/2019 Object Oriented Lecture Notes

    7/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Lecture 8 (Tue): Function Templates

    1 Why function templates?

    2 What are function templates?

    3 Type and nontype parameters

    4

    Two compilation models5 Instantiation

    6 Template argument deduction

    7 Specialisation

    8 Function template Overloading

    9 Self-Reading Material: header files

    7

    Wh f ti t l t ? Wh t f ti t l t ? T d t t T il ti d l I t ti ti

    http://-/?-http://-/?-
  • 7/29/2019 Object Oriented Lecture Notes

    8/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Why Function Templates?

    As a strongly-typed language, C++ requires:

    int min(int a, int b) { 1r e t u r n a < b ? a : b ;

    }

    double min(double a, double b) { // 2

    r e t u r n a < b ? a : b ;}... more for other types ...

    Call resolution due to function overloading:

    min(1, 2); // 1

    min(1.1, 2.2); // 2

    ...

    C++ FAQ-lite 9.5 (macros are evil)

    Read: http://www.gotw.ca/gotw/077.htm

    8

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    9/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Lecture 8 (Tue): Function Templates

    1 Why function templates?

    2 What are function templates?

    3 Type and nontype parameters

    4 Two compilation models

    5 Instantiation

    6 Template argument deduction

    7 Specialisation

    8 Function template Overloading

    9 Self-Reading Material: header files

    9

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    http://-/?-http://-/?-
  • 7/29/2019 Object Oriented Lecture Notes

    10/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    What Are Function Templates?

    Definition:template

    T min(T a, T b) {r e t u r n a < b ? a : b ;

    }

    Uses:

    min(1, 2) // int min(int, int)

    min(1.1, 2.2) // double min(double, double)

    ...

    NB

    A function template is a prescription for the compiler to generateparticular instances of a function varying by type

    10

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    11/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Template Parameter List

    type-dependent interface

    type-independent body

    template

    T min(T a, T b) {

    r e t u r n a < b ? a : b ;}

    Separation of type-dependent from type-independent parts

    T:

    called a template type parametera placeholder for any built-in or user-defined typeHistorically, class can also be used instead of typename

    11

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    12/44

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Lecture 8 (Tue): Function Templates

    1 Why function templates?

    2 What are function templates?

    3 Type and nontype parameters

    4 Two compilation models

    5 Instantiation

    6 Template argument deduction

    7 Specialisation8 Function template Overloading

    9 Self-Reading Material: header files

    12

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    http://-/?-http://-/?-
  • 7/29/2019 Object Oriented Lecture Notes

    13/44

    y p p yp yp p p

    Type and Nontype Parameters

    template

    T findmin(T (&a)[size]) {T min = a[0];

    for (int i = 1; i < size; i++)

    if (a[i] < min) min = a[i];

    return min;

    }int main() {

    int x[] = { 3, 1, 2 };double y[] = { 3.3, 1.1, 2.2, 4.4};

    cout

  • 7/29/2019 Object Oriented Lecture Notes

    14/44

    y p p yp yp p p

    Type and Nontype ParametersThe compiler generates two instances of min:

    int findmin(int (&a)[3]) {int min = a[0];for (int i = 1; i < 3; i++)

    if (a[i] < min) min = a[i];

    return min;

    }double findmin(double (&a)[4]) {

    double min = a[0];

    for (int i = 1; i < 3; i++)

    if (a[i] < min) min = a[i];

    return min;}

    NB

    Problem: code explosion different instances generated even for

    arrays of ints with different sizes14

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    15/44

    Type Equivalence and Nontype Parametertemplate

    T findmin(T (&a)[size]) {T min = a[0];

    for (int i = 1; i < size; i++)

    if (a[i] < min) min = a[i];

    return min;

    }int main() {

    int x[] = { 3, 1, 2 };const int sz = 3;

    int y[sz];

    findmin(x); // instantiates findmin(int (&)[3])findmin(y); // same instantiation

    }

    NB

    Expressions that evaluate to the same value are consideredequivalent template arguments for nontype parameters15

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    16/44

    Lecture 8 (Tue): Function Templates

    1 Why function templates?

    2 What are function templates?

    3 Type and nontype parameters

    4 Two compilation models

    5 Instantiation

    6 Template argument deduction

    7Specialisation

    8 Function template Overloading

    9 Self-Reading Material: header files

    16

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    http://-/?-http://-/?-
  • 7/29/2019 Object Oriented Lecture Notes

    17/44

    Inclusion Compilation Model// min.h:template T min(T a, T b);// other declarations

    #include min.tem

    // user-file1.cpp:#include min.hmin(1, 2);min(1.1, 2.2);

    // user-file2.cpp:#include min.hmin(1, 2);min(p, q);

    // min.tem:template T min(T a, T b) {

    return a < b ? a : b;}

    Templates in header files and compile only .cpp filesDifferent instantiations may be generated but the compilershould behave as if only one int min(int, int) were instantiatedDrawbacks:

    implementation details available in .h files

    compiling the same template many times can be slow17

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    18/44

    Separation Compilation Model

    // min.h:export template T min(T a, T b);

    // user-file.h:#include min.h

    min(1, 2);min(1.1, 2.2);

    // min.cpp: // not min.tem any more!#include min.h

    template T min(T a, T b) {return a < b ? a : b;

    }

    The declarations of function templates in header files and

    definitions in separate text filesOvercoming the two drawbacks of the inclusion model:interface and implementation separatedthe same template definition compiled once

    Theoretically appealing but rarely supported in practice

    Why export and why difficult to implement:http://drdobbs.com/18440158418

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    19/44

    Advice on Using and Compiling Function Templates

    GNU C++ does not support the separation model

    Rarely does a compiler have such a support

    Place your function templates in .h files and include themwhere they are used (as shown in these slides)

    five models: http://www.cs.indiana.edu/cgi-

    bin/techreports/TRNNN.cgi?trnum=TR543

    19

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    20/44

    Lecture 8 (Tue): Function Templates

    1 Why function templates?

    2 What are function templates?

    3 Type and nontype parameters

    4 Two compilation models

    5 Instantiation

    6 Template argument deduction

    7

    Specialisation8 Function template Overloading

    9 Self-Reading Material: header files

    20

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    http://-/?-http://-/?-
  • 7/29/2019 Object Oriented Lecture Notes

    21/44

    Function Template Instantiation

    template T min(T a, T b) {

    r e t u r n a < b ? a : b ;

    }

    cout

  • 7/29/2019 Object Oriented Lecture Notes

    22/44

    Name Resolution

    Two parties involved about a function template:designerclient

    Two-step lookup in name resolution:

    Type-independent names: resolved at the definition oftemplate designer provides the declarationsType-dependent names: resolved at the point of instantiation client provides the declarations

    If there are multiple points, compiler chooses one of these as

    the point of instantiation for the template= client places all declarations required in header files

    Q1, Week 9 Tutorial

    22

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    23/44

    Name Resolution

    Template definition:void print(const char* s) { cout

  • 7/29/2019 Object Oriented Lecture Notes

    24/44

    Lecture 8 (Tue): Function Templates

    1 Why function templates?

    2 What are function templates?

    3 Type and nontype parameters

    4 Two compilation models

    5 Instantiation

    6 Template argument deduction

    7 Specialisation

    8 Function template Overloading

    9 Self-Reading Material: header files

    24

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    http://-/?-http://-/?-
  • 7/29/2019 Object Oriented Lecture Notes

    25/44

    Template Argument Deduction

    Two kinds of template parameters:Template parameters (type or nontype)Call parameters

    Key observation: both are related

    Deduction: the process of determining the types (of typeparameters) and values of nontype parameters from the typesof the function arguments

    The return type is ignored

    NB

    No argument deduction for class templates (Thur)!

    25

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    26/44

    Template Argument Deduction

    min:type parameter

    template

    T min(T a, T b) {r e t u r n a < b ? a : b ;

    }

    call parameters

    Deduction:

    min(1, 2); ==> int min(int, int)

    min(1.1, 2.2); ==> double min(double, double)

    The return type is irrelevant:

    int i = min(1, 2); // int min(int, int)

    double i = min(1, 2); // int min(int, int)

    26

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    27/44

    Template Argument Deduction

    findmin: nontype parametertype parameter

    template

    T findmin(T (&a)[size]) {T min = a[0];

    for (int i = 1; i < size; i++)

    if (a[i] < min) min = a[i];return min;

    }call parameters

    Deduction:

    int x[] = { 3, 1, 2 };findmin(x); ==> int findmin((&)[3]);

    double y[] = { 3.3, 1.1, 2.2, 4.4};findmin(y) ==> double findmin((&)[4]);

    27

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    28/44

    Limited Conversions for Type Paramete Arguments

    Only three kinds of implicit conversions for type parameters:

    lvalue transformation, e.g.,DEF: template f(T* array) { }

    USE: int a[] = {1, 2}; f(a); // array to pointer

    qualification conversion (const and volatile)

    DEF: template f(const T* array) {}

    USE: int a[] = {1, 2};

    int *pa = &a; f(pa); // int* => const int*

    conversion to a base class from a derived class

    DEF: template void f(Base &a) { }

    USE: template

    class Derived : public Base { ... }

    Derived d;

    f(d);

    Usual conversions done for nontype parameters

    28

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    29/44

    Explicit Template Arguments

    In template argument deduction, all deducted types for the

    same template parameter must be the same

    min(1.0, 2); // compile-time error

    1.0 ==> T is double

    2 ==> T is int

    Explicit template arguments: override the template argumentdeduction mechanism by explicitly specifying the types of thearguments to be used

    int i; double d

    min(i, static_castd); // int min(int, int)min(i, d); // int min(int, int)

    min(static_casti, d); // double min(double, double)

    min(i, d); // double min(double, double)

    29

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    30/44

    Explicit Template Arguments

    Neither T nor U works as return type

    template ??? sum(T, U);

    sum(3, 4L); // 2nd type is larger ==> want U sum(T, U)

    sum(3L, 4); // 1st type is larger ==> want T sum(T, U)

    Using a type parameter for the return type:

    template

    T1 sum(T2, T3);

    long v = sum(3, 4L); // calls long sum(int, long)

    long v = sum(3L, 4); // calls long sum(long, int)

    The return type T1 cannot be deducedT1 must be the 1st since the explicit arguments are matchedto the corresponding template parameters from left to right

    30

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    31/44

    Zero Initialisation

    x has an undefined value if T is a built-in type:

    template

    void foo(T y)

    {

    T x;

    }

    Ensure proper default initialisation:

    template void foo(T y)

    {

    T x = T();

    }

    Default constructors (initialised to 0): int(), float(), ...Some question being asked in the past:

    int *p = new int[10]; // an array of 10 ints uninitialised

    int *p = new int[10](); // initialised to 0 (using int())

    UserType *p = new UserType[10]; // default ctor called

    UserType *p = new UserType[10](); // default ctor called

    31

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

  • 7/29/2019 Object Oriented Lecture Notes

    32/44

    Lecture 8 (Tue): Function Templates

    1 Why function templates?

    2 What are function templates?

    3 Type and nontype parameters

    4 Two compilation models

    5 Instantiation

    6 Template argument deduction

    7 Specialisation

    8 Function template Overloading

    9 Self-Reading Material: header files

    32

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    http://-/?-http://-/?-
  • 7/29/2019 Object Oriented Lecture Notes

    33/44

    SpecialisationNeeded for correctness or efficiency reasons or bothThe semantics of min for char are wrong:

    template

    T min(T a, T b) {r e t u r n a < b ? a : b ;

    }

    The correct version:typedef const char* PCC;

    template PCC min(PCC a, PCC b) {return (strcmp(a, b) < 0) ? a : b;

    }

    Exact match required (no conversions for the arguments)Client code:

    min("abc", "xyz");

    NB

    Sutters Mill: Why not specialize Function Templates?

    http://www.ddj.com/cpp/18440141333

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    S O

  • 7/29/2019 Object Oriented Lecture Notes

    34/44

    Specialisation File Organisation

    // min.h:

    template T min(T a, T b) {

    r e t u r n a < b ? a : b ;

    }

    typedef const char *PCC;

    template PCC min(PCC a, PCC b);

    // min-specialisation.cpp:

    #include "min.h"

    // the specialised min implementation goes here

    // min-user.cpp:

    #include "min.h"

    // ...

    Guaranteed that the specialisation must be visible in every fileOtherwise, the specialisation may be in some but not all files34

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    L 8 (T ) F i T l

  • 7/29/2019 Object Oriented Lecture Notes

    35/44

    Lecture 8 (Tue): Function Templates

    1 Why function templates?

    2 What are function templates?

    3 Type and nontype parameters

    4 Two compilation models

    5 Instantiation

    6 Template argument deduction

    7 Specialisation

    8 Function template Overloading

    9 Self-Reading Material: header files

    35

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    F i T l O l di

    http://-/?-http://-/?-
  • 7/29/2019 Object Oriented Lecture Notes

    36/44

    Function Template Overloading

    template min(T a, T b);

    typedef const char* PCC;

    template PCC Min(PCC a, PCC b);

    double min(double a, double b)

    const char* s1 = "abc", *s2 = "xyz";

    cout

  • 7/29/2019 Object Oriented Lecture Notes

    37/44

    ExerciseDoes each of the following two programs compile?

    #include

    #include

    int main() {

    vector v;

    find(v.begin(), v.end(), 1);

    }

    #include

    #include

    class X {

    public:

    X () { }

    };

    int main() {

    vector v;

    find(v.begin(), v.end(), X());}

    Add to class X: bool operator==(const X &m) { ... }

    Why? Two-step name resolution!

    37

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    R di

  • 7/29/2019 Object Oriented Lecture Notes

    38/44

    Reading

    Chapter 16, C++ Primer:

    Chapter 5, Bruce Eckel, Thinking in C++, Vol 2

    C++ FAQ Lite: templates:http://www.parashift.com/c++-faq-lite/templates.html

    Next Class: Class Templates

    38

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Lecture 8 (Tue): Function Templates

  • 7/29/2019 Object Oriented Lecture Notes

    39/44

    Lecture 8 (Tue): Function Templates

    1 Why function templates?

    2 What are function templates?

    3 Type and nontype parameters

    4 Two compilation models

    5 Instantiation

    6 Template argument deduction

    7 Specialisation

    8 Function template Overloading

    9 Self-Reading Material: header files

    39

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    What Are Found Typically in a Header File

    http://-/?-http://-/?-
  • 7/29/2019 Object Oriented Lecture Notes

    40/44

    What Are Found Typically in a Header File

    class Stack; // class declaration

    class Stack { ... }; // class definition

    template class stack;

    template class stack { ... }

    inline void f() { ... }int* g(int);

    extern int i;

    const double pi = 3.1415926;

    enumeration Color { RED, GREEN, BLUE };

    typedef void* (*f)(*int) FP;#include

    40

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    What Cannot be Placed in a Header File

  • 7/29/2019 Object Oriented Lecture Notes

    41/44

    What Cannot be Placed in a Header File

    No variable definitions i multiply defined

    header.h:

    int i = 1;

    file1.cpp:

    #include "header.h"

    file2.cpp:

    #include "header.h"

    No function definitions f multiply defined

    header.h:

    void f() { ... }

    file1.cpp:

    #include "header.h"

    file2.cpp:

    #include "header.h"

    41

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    One Definition Rule (ODR)

  • 7/29/2019 Object Oriented Lecture Notes

    42/44

    One-Definition-Rule (ODR)

    An entity has exactly one definition in a program

    But the entity need not to be defined if not used

    int f(int); // known as ZDR (Zero Definition Rule)

    extern int i;

    class Stack;

    int main () { Stack *sp; } // compiles ok

    Ideally, a definition should reside in exactly one file, but this isdifficult to enforce to due separate compilation

    ODR: Two definitions of a class, template, or inline function

    is accepted as the same unique definition iff1 They are in different translation units,2 they are token-for-token identical, and3 the meanings of those tokens are identical

    42

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    Some Violations of ODR

  • 7/29/2019 Object Oriented Lecture Notes

    43/44

    Some Violations of ODR

    (1)file1.cpp: file2.cpp

    class Point { int x; int y} class Point { int a; int b}

    (2)

    file1.cpp: file2.cpp

    class Point { int x; int y} class Point { int x; char y}(3)

    file1.cpp: file2.cpp

    class Point { int x; int y} class Point { int x; }

    These programs compile under most implementations errors not caught by linkers

    Use #include to reduce this kind of violations

    43

    Why function templates? What are function templates? Type and nontype parameters Two compilation models Instantiation

    One-Definition-Rule

  • 7/29/2019 Object Oriented Lecture Notes

    44/44

    One-Definition-Rule

    A head file can contain:

    class declarations and definitions

    template declarations and definitions

    inline function definitions

    variable (data) declarations

    but notvariable (data) and function definitions

    Why allowing definitions in header file at all?

    Inline functions inlining

    Class definitions Object Layout (Lecture 3):Class templates instantiations (Lecture 4)

    struct X; // does this compile in C?

    struct X x; // remember separate compilation?

    44