Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

C++ Templates: Parametric Polymorphism and Function Templates in CSE333, Autumn 2018, Study notes of C programming

An outline for lecture 14 of the CSE333 course at the University of X, focusing on C++ templates. The instructor, Hal Perkins, discusses the concept of parametric polymorphism and function templates. Students are introduced to the idea of writing 'generic code' that is type-independent and compile-time polymorphic. examples of template functions and compiler inference, as well as non-type templates. The lecture also covers class templates and their use in creating a pair class.

Typology: Study notes

2021/2022

Uploaded on 09/12/2022

ekavir
ekavir 🇺🇸

4.3

(31)

257 documents

1 / 19

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CSE333, Autumn 2018L14: C++ Templates
C++ Templates
CSE 333 Autumn 2018
Instructor: Hal Perkins
Teaching Assistants:
Tarkan Al-Kazily Renshu Gu Travis McGaha
Harshita Neti Thai Pham Forrest Timour
Soumya Vasisht Yifan Xu
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13

Partial preview of the text

Download C++ Templates: Parametric Polymorphism and Function Templates in CSE333, Autumn 2018 and more Study notes C programming in PDF only on Docsity!

C++ Templates

CSE 333 Autumn 2018

Instructor: Hal Perkins

Teaching Assistants:

Tarkan Al-Kazily Renshu Gu Travis McGaha

Harshita Neti Thai Pham Forrest Timour

Soumya Vasisht Yifan Xu

Administrivia v Homework 2 due tomorrow (10/25) § File system crawler, indexer, and search engine § Don’t forget to clone your repo to double-/triple-/quadruple-check

compilation, execution, and tests!

  • If your code won’t build or run when we clone it, well, you should have

caught that…

v Midterm: Friday, 11/2 in class § Closed book, no notes § Old exams and topic list on the course web now

  • Everything up through C++ classes, dynamic memory, templates & STL § Review in sections next week v No new exercises due until after hw1 due

Suppose that… v You want to write a function to compare two ints v You want to write a function to compare two strings § Function overloading! // returns 0 if equal, 1 if value1 is bigger, - 1 otherwise int compare (const int &value1, const int &value2) { if (value1 < value2) return - 1 ; if (value2 < value1) return 1 ; return 0 ; } // returns 0 if equal, 1 if value1 is bigger, - 1 otherwise int compare (const int &value1, const int &value2) { if (value1 < value2) return - 1 ; if (value2 < value1) return 1 ; return 0 ; } // returns 0 if equal, 1 if value1 is bigger, - 1 otherwise int compare (const string &value1, const string &value2) { if (value1 < value2) return - 1 ; if (value2 < value1) return 1 ; return 0 ; }

Hm… v The two implementations of compare are nearly identical! § What if we wanted a version of compare for every comparable type? § We could write (many) more functions, but that’s obviously wasteful and redundant v What we’d prefer to do is write “ generic code ” § Code that is type-independent § Code that is compile-type polymorphic across types

Function Templates v Template to compare two “things”: #include #include // returns 0 if equal, 1 if value1 is bigger, - 1 otherwise template // <...> can also be written int compare (const T &value1, const T &value2) { if (value1 < value2) return - 1 ; if (value2 < value1) return 1 ; return 0 ; } int main (int argc, char **argv) { std::string h("hello"), w("world"); std::cout << compare ( 10 , 20 ) << std::endl; std::cout << compare <std::string>(h, w) << std::endl; std::cout << compare (50.5, 50.6) << std::endl; return 0 ; }

functiontemplate.cc

Compiler Inference v Same thing, but letting the compiler infer the types: #include #include // returns 0 if equal, 1 if value1 is bigger, - 1 otherwise template int compare (const T &value1, const T &value2) { if (value1 < value2) return - 1 ; if (value2 < value1) return 1 ; return 0 ; } int main (int argc, char **argv) { std::string h("hello"), w("world"); std::cout << compare ( 10 , 20 ) << std::endl; // ok std::cout << compare (h, w) << std::endl; // ok std::cout << compare ("Hello", "World") << std::endl; // hm… return 0 ; }

functiontemplate_infer.cc

What’s Going On? v The compiler doesn’t generate any code when it sees the template function § It doesn’t know what code to generate yet, since it doesn’t know what types are involved v When the compiler sees the function being used, then it understands what types are involved § It generates the instantiation of the template and compiles it (kind of like macro expansion)

  • The compiler generates template instantiations for each type used as

a template parameter

This Creates a Problem #include #include "compare.h" using namespace std; int main (int argc, char **argv) { cout << comp ( 10 , 20 ); cout << endl; return 0 ; } #include "compare.h" template int comp (const T& a, const T& b) { if (a < b) return - 1 ; if (b < a) return 1 ; return 0 ; } #ifndef COMPARE_H #define COMPARE_H template int comp (const T& a, const T& b); #endif // COMPARE_H

compare.h

compare.cc

main.cc

Solution # #include #include "compare.h" using namespace std; int main (int argc, char **argv) { cout << comp ( 10 , 20 ); cout << endl; return 0 ; } template int comp (const T& a, const T& b) { if (a < b) return - 1 ; if (b < a) return 1 ; return 0 ; } #ifndef COMPARE_H #define COMPARE_H template int comp (const T& a, const T& b); #include "compare.cc" #endif // COMPARE_H

compare.h

compare.cc

main.cc

Class Templates v Templates are useful for classes as well § (In fact, that was one of the main motivations for templates!) v Imagine we want a class that holds a pair of things that we can: § Set the value of the first thing § Set the value of the second thing § Get the value of the first thing § Get the value of the second thing § Swap the values of the things § Print the pair of things

Pair Function Definitions template void Pair:: set_first (Thing &copyme) { first_ = copyme; } template void Pair:: set_second (Thing &copyme) { second_ = copyme; } template void Pair:: Swap () { Thing tmp = first_; first_ = second_; second_ = tmp; } template std::ostream &operator<<(std::ostream &out, const Pair& p) { return out << "Pair(" << p. get_first () << ", " << p. get_second () << ")"; }

Pair.cc

Using Pair #include #include #include "Pair.h" int main (int argc, char** argv) { Pair<std::string> ps; std::string x("foo"), y("bar"); ps. set_first (x); ps. set_second (y); ps. Swap (); std::cout << ps << std::endl; return 0 ; }

usepair.cc

Review Questions (both template and class issues) v Why are only get_first() and get_second() const? v Why do the accessor methods return Thing and not references? v Why is operator<< not a friend function? v What happens in the default constructor when Thing is a class? v In the execution of Swap(), how many times are each of the following invoked (assuming Thing is a class)?

ctor ____ cctor ____ op= ____ dtor ____