C++ Templates CSE 333 Spring 2018

Slides:



Advertisements
Similar presentations
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Advertisements

Chapter 16 Templates. Copyright © 2006 Pearson Addison-Wesley. All rights reserved Learning Objectives  Function Templates  Syntax, defining 
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Intro to Generic Programming Templates and Vectors.
CSIS 123A Lecture 12 Templates. Introduction  C++ templates  Allow very ‘general’ definitions for functions and classes  Type names are ‘parameters’
Templates Zhen Jiang West Chester University
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - Templates Outline 11.1 Introduction 11.2 Function Templates 11.3 Overloading Function Templates.
Templates An introduction. Simple Template Functions template T max(T x, T y) { if (x > y) { return x; } else { return y; } } int main(void) { int x =
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 4 is due Nov. 20 (next Friday). After today you should know everything you need for assignment.
System Programming Practical Session 7 C++ Memory Handling.
Chapter 16 Templates Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
1 Another Example: Complex Class #ifndef _Complex_H #define _Complex_H class Complex { float re, im; // by default private public: Complex(float x = 0,
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Motivation for Generic Programming in C++
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
C++ Templates.
Templates.
Chapter 14 Templates C++ How to Program, 8/e
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Pointers, Pointers, Pointers CSE 333 Spring 2018
Friday, January 26, 2018 Announcements… For Today… For Next Time…
Templates.
The dirty secrets of objects
Server-side Programming CSE 333 Spring 2018
C++ References, Const, Classes CSE 333 Spring 2018
C++ Inheritance II, Casting CSE 333 Spring 2018
C++ Standard Template Library CSE 333 Spring 2018
C++ Intro CSE 333 Spring 2018 Instructor: Justin Hsia
C++ Constructor Insanity CSE 333 Spring 2018
Client-side Networking CSE 333 Spring 2018
C++ Encapsulation, Heap CSE 333 Spring 2018
Name: Rubaisha Rajpoot
CMSC 202 Templates.
Chapter 17 Templates. Chapter 17 Templates Overview 17.1 Templates for Algorithm Abstraction 17.2 Templates for Data Abstraction.
CMSC 202 Lesson 22 Templates I.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
C++ Inheritance I CSE 333 Spring 2018
C++ STL, Smart Pointers Intro CSE 333 Spring 2018
C++ Smart Pointers CSE 333 Spring 2018
CISC/CMPE320 - Prof. McLeod
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
References Revisited CSE 333 Spring 2018
References Revisited CSE 333 Summer 2018
Fall 2018 CISC124 2/24/2019 CISC124 Quiz 1 marking is complete. Quiz average was about 40/60 or 67%. TAs are still grading assn 1. Assn 2 due this Friday,
C++ Templates CSE 333 Summer 2018
C++ Constructor Insanity CSE 333 Summer 2018
C++ Class Details, Heap CSE 333 Summer 2018
Concurrency and Processes CSE 333 Spring 2018
Templates I CMSC 202.
C++ Templates CSE 333 Autumn 2018
C++ Constructor Insanity CSE 333 Autumn 2018
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
C++ Constructor Insanity CSE 333 Winter 2019
References Revisited CSE 333 Autumn 2018
CMSC 202 Lesson 6 Functions II.
References Revisited CSE 333 Winter 2019
C++ Templates An Introduction to Generic Programming.
Lesson 25 Miscellaneous Topics
EECE.3220 Data Structures Instructor: Dr. Michael Geiger Spring 2019
C++ Templates CSE 333 Winter 2019
Templates An introduction.
Class rational part2.
Chapter 11 - Templates Outline Introduction Function Templates Overloading Function Templates Class Templates Class.
Templates CMSC 202, Version 4/02.
C++ Constructor Insanity CSE 333 Spring 2019
C++ Standard Template Library CSE 333 Spring 2019
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
(4 – 2) Introduction to Classes in C++
SPL – PS1 Introduction to C++.
Presentation transcript:

C++ Templates CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon Huang Wei Lin

Administrivia Exercise 11 released today, due Wednesday Modify your Vector class to use the heap Refer to Str.h/Str.cc Homework 2 due Thursday (4/26) File system crawler, indexer, and search engine Don’t forget to clone your repo to double-/triple-/quadruple-check compilation! Midterm: next Friday (5/4) from 5-6 pm in GUG 220 Let me know ASAP if you have a conflict!

Lecture Outline Templates

Suppose that… You want to write a function to compare two ints 4/23/2018 Suppose that… You want to write a function to compare two ints 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; } int compare(const string &value1, const string &value2) {

Hm… The two implementations of compare are nearly identical! What if we needed a version of compare for every comparable type? What we’d prefer to do is write “generic code” Code that is type-independent Code that is compile-type polymorphic across types

C++ Parametric Polymorphism C++ has the notion of templates A function or class that accepts a type as a parameter You define the function or class once in a type-agnostic way When you invoke the function or instantiate the class, you specify (one or more) types or values as arguments to it At compile-time, the compiler will generate the “specialized” code from your template using the types you provided Your template definition is NOT code Code is only generated if you use your template

Function Templates Template to compare two “things”: 4/23/2018 Function Templates Template to compare two “things”: #include <iostream> #include <string> // returns 0 if equal, 1 if value1 is bigger, -1 otherwise template <typename T> 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<int>(10, 20) << std::endl; std::cout << compare<std::string>(h, w) << std::endl; std::cout << compare<double>(50.5, 50.6) << std::endl; in template, "class" is traditional, but may see "typename" instead functiontemplate.cc

4/23/2018 Compiler Inference Same thing, but letting the compiler infer the types: #include <iostream> #include <string> // returns 0 if equal, 1 if value1 is bigger, -1 otherwise template <typename T> 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… in template, "class" is traditional, but may see "typename" instead functiontemplate_infer.cc

4/23/2018 Template Non-types You can use non-types (constant values) in a template: #include <iostream> #include <string> // prints a value out N times template <typename T, int N> int printmultiple(const T &value1) { for (int i = 0; i < N; ++i) { std::cout << value1 << std::endl; } int main(int argc, char **argv) { std::string h("hello"); printmultiple<std::string, 3>(h); printmultiple<const char *, 4>("hi"); printmultiple<int, 5>(10); return 0; in template, "class" is traditional, but may see "typename" instead nontypeparameter.cc

What’s Going On? 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 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 compare.h main.cc compare.cc 4/23/2018 This Creates a Problem #ifndef _COMPARE_H_ #define _COMPARE_H_ template <typename T> int comp(const T& a, const T& b); #endif // _COMPARE_H_ #include <iostream> #include "compare.h" using namespace std; int main(int argc, char **argv) { cout << comp<int>(10, 20); cout << endl; return 0; } compare.h main.cc #include "compare.h" template <typename T> int comp(const T& a, const T& b) { if (a < b) return -1; if (b < a) return 1; return 0; } compare.cc

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

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

Peer Instruction Question 4/23/2018 Peer Instruction Question Assume we are using Solution #2 (.h includes .cc) Which is the best way to compile our program (a.out)? Vote at http://PollEv.com/justinh A. g++ main.cc B. g++ main.cc compare.cc C. g++ main.cc compare.h D. g++ -c main.cc g++ -c compare.cc g++ main.o compare.o E. We’re lost…

Class Templates Templating is useful for classes as well! 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 Class Definition Pair.h #ifndef _PAIR_H_ #define _PAIR_H_ 4/23/2018 Pair Class Definition Pair.h #ifndef _PAIR_H_ #define _PAIR_H_ template <typename Thing> class Pair { public: Pair() { }; Thing get_first() const { return first_; } Thing get_second() const { return second_; } void set_first(Thing &copyme); void set_second(Thing &copyme); void Swap(); private: Thing first_, second_; }; #include "Pair.cc" #endif // _PAIR_H_ in template, "class" is traditional, but may see "typename" instead

Pair Function Definitions 4/23/2018 Pair Function Definitions Pair.cc template <typename Thing> void Pair<Thing>::set_first(Thing &copyme) { first_ = copyme; } void Pair<Thing>::set_second(Thing &copyme) { second_ = copyme; void Pair<Thing>::Swap() { Thing tmp = first_; first_ = second_; second_ = tmp; template <typename T> std::ostream &operator<<(std::ostream &out, const Pair<T>& p) { return out << "Pair(" << p.get_first() << ", " << p.get_second() << ")"; in template, "class" is traditional, but may see "typename" instead

Using Pair usepair.cc #include <iostream> 4/23/2018 Using Pair usepair.cc #include <iostream> #include <string> #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; } in template, "class" is traditional, but may see "typename" instead

Class Template Notes Thing is replaced with template argument when class is instantiated The class template parameter name is in scope of the template class definition and can be freely used there Class template member functions are template functions with template parameters that match those of the class template These member functions must be defined as template function outside of the class template definition The template parameter name does not need to match that used in the template class definition, but really should Only template methods that are actually called in your program are instantiated

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