Templating functions. Comp Sci 1570 Introduction to C++ Administrative notes. Review. Templates. Compiler processing. Functions Overloading

Similar documents
Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

COEN244: Class & function templates

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

Inheritance and Overloading. Week 11

More on Functions. Lecture 7 COP 3014 Spring February 11, 2018

Arrays in C++ Instructor: Andy Abreu

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Lesson 13 - Vectors Dynamic Data Storage

I m sure you have been annoyed at least once by having to type out types like this:

Arrays. myints = new int[15];

Introduction to Core C++

C++ TEMPLATES. Templates are the foundation of generic programming, which involves writing code in a way that is independent of any particular type.

Constructors for classes

Developed By : Mrs. K. M. Sanghavi

2SKILL. Variables Lesson 6. Remembering numbers (and other stuff)...

Object Oriented Design

Tree traversals and binary trees

COM S 213 PRELIM EXAMINATION #2 April 26, 2001

Cpt S 122 Data Structures. Templates

Type Inference auto for Note: Note:

Structs. Comp Sci 1570 Introduction to C++ Introduction. Aggregate data. Example. General syntax Object initialization Initialization and access

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

COMP 250 Winter 2011 Reading: Java background January 5, 2011

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Introduction to Standard C++

Lesson 11: Generic Programming. EE3490E: Programming S1 2018/2019 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Function Templates. Consider the following function:

PIC 10A Objects/Classes

Review of Important Topics in CS1600. Functions Arrays C-strings

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

Inheritance, Polymorphism, and Interfaces

Template. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong

C++ Programming Fundamentals

C++ 11 and the Standard Library: Containers, Iterators, Algorithms

C++ Exception Handling 1

D Programming Language

Introduction to C++ Part II. Søren Debois. Department of Theoretical Computer Science IT University of Copenhagen. September 12th, 2005

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CMSC202 Computer Science II for Majors

Part Tests on TBMaster

Variables and numeric types

Exercise: Inventing Language

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Advanced C++ Topics. Alexander Warg, 2017

CS93SI Handout 04 Spring 2006 Apr Review Answers

Software Design and Analysis for Engineers

Object-Oriented Programming

Sixth lecture; classes, objects, reference operator.

C The new standard

More loops Ch

Prelim 1. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants

Installing and Using Dev-C++

Object Oriented Design

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

void setup(){ void loop() { The above setup works, however the function is limited in the fact it can not be reused easily. To make the code more gene

My First Command-Line Program

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Last class. -More on polymorphism -super -Introduction to interfaces

COSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26

COMP s1 Lecture 1

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

C++ for Java Programmers

BIS1523 Homework Assignments 2.1

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

Variadic functions: Variadic templates or initializer lists? -- Revision 1

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

M.CS201 Programming language

8. Functions (II) Control Structures: Arguments passed by value and by reference int x=5, y=3, z; z = addition ( x, y );

Objective 1: Familiarize yourself with basic database terms and definitions. Objective 2: Familiarize yourself with the Access environment.

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Subtracting with Multi-Digit Numbers Adaptable for 2 nd, 3 rd, 4 th, and 5 th grades*

TEMPLATE IN C++ Function Templates

Carleton University COMP1406/1006, Summer 2013 Tutorial 2

Item 1: Switching Streams

Reminder: compiling & linking

ENGI 1020 Introduction to Computer Programming R E Z A S H A H I D I J U L Y 2 6,

C++ For Science and Engineering Lecture 15

CS Problem Solving and Object-Oriented Programming

CS260 program assignment #3 (30 points, check the schedule for the due date)

Getting Started with Amicus Document Assembly

Basic Templates Intro

Introduction to Computer Science I

Objects and Classes. Amirishetty Anjan Kumar. November 27, Computer Science and Engineering Indian Institue of Technology Bombay

CSE 333 Final Exam 3/19/14

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Default arguments, documentation

CAP Fundamentos de Programação Estruturada Aula 9 STL. Lubia Vinhas

Programming Languages: OO Paradigm, Polymorhism and Class Members

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Instructions for Crossword Assignment CS130

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.

Creating a Box-and-Whisker Graph in Excel: Step One: Step Two:

Classes Ch

The sequence of steps to be performed in order to solve a problem by the computer is known as an algorithm.

Lecture 10: building large projects, beginning C++, C++ and structs

Chapter 3 Function Overloading

CSci 1113 Final. Name: Student ID:

Transcription:

s s in Templating functions Comp Sci 1570 Introduction to

Outline s s in 1 2 3 s s in 4

Test 1 grade distribution grade on y, each student on x, sorted by y s s in 50 or below should talk to me.

Outline s s in 1 2 3 s s in 4

Outline s s in 1 2 3 s s in 4

help efficiency and code re-use s s in We have learned how to write functions that help make programs easier to write, safer, and more maintainable. i n t max( i n t x, i n t y ) { return ( x > y )? x : y ; }

Outline s s in 1 2 3 s s in 4

simplifies applying functions to types s s in i n t max( i n t x, i n t y ) { return ( x > y )? x : y ; } double max( double x, double y ) { return ( x > y )? x : y ; } To re-use function names, we can overload functions. The body of the double version of max() is exactly the same as for the int version of max()! Implementation would work for all sorts of different types: chars, ints, doubles, and event strings. However, because requires you to make your variables specific types, you re stuck writing one function for each type you wish to use.

Outline s s in 1 2 3 s s in 4

s s s in What is the general definition of a template?

Outline s s in 1 2 3 s s in 4

s s s in A template is a model that serves as a pattern for creating similar objects One type of template that is very easy to understand is that of a stencil. A stencil is an object (e.g. a piece of cardboard) with a shape cut out of it (eg. the letter J). By placing the stencil on top of another object, then spraying paint through the hole, you can very quickly produce stenciled patterns in many different colors! Note that you only need to create a given stencil once. You can then use it as many times as you like, to create stenciled patterns in whatever color(s) you like. Even better, you don t have to decide the color of the stenciled pattern you want to create until you decide to actually use the stencil.

Outline s s in 1 2 3 s s in 4

Templating functions in s s in A template is a blueprint or formula for creating a generic class or a function. s are the foundation of generic programming, which involves writing code in a way that is independent of any particular type. We define the function using placeholder types, called template typename. Once we have created a function using these placeholder types, we have effectively created a function stencil. The general form of a template function definition is shown here: template <typename type> r e t t y p e func name ( p a r a m e t e r l i s t ) { // body o f f u n c t i o n }

Outline s s in 1 2 3 s s in 4

s s in You can name your placeholder types almost anything you want, so long as it s not a reserved word. However, in, it s customary to name your template types the letter T (short for Type ). Here s our new function with a placeholder type: T max(t x, T y ) { return ( x > y )? x : y ; } This is a good start however, it won t compile because the compiler doesn t know what T is!

Outline s s in 1 2 3 s s in 4

s s in In order to make this work, we need to tell the compiler two things: First, that this is a template definition Second, that T is a placeholder type. We can do both of those things in one line, using what is called a template : // t h i s i s the t e m p l a t e d e c l a r a t i o n template <typename T> T max(t x, T y ) { return ( x > y )? x : y ; }

Outline s s in 1 2 3 s s in 4

s s in If the template function uses multiple template type, they can be separated by commas: template <typename T1, typename T2> // t e m p l a t e f u n c t i o n h e r e

Outline s s in 1 2 3 s s in 4

Example s s in template<c l a s s TYPE> void P r i n t T w i c e (TYPE data ) { cout<< Twice : << data 2 << e n d l ; }

s s in The first line of code: template<c l a s s TYPE> tells the compiler that this is a function-template. The actual meaning of TYPE would be deduced by compiler depending on the argument passed to this function. Here, the name, TYPE is known as template type.

s s in For instance, if we call the function as: P r i n t T w i c e ( 1 2 4 ) ; TYPE would be replaced by compiler as int, and compiler would instantiate this template-function as: void P r i n t T w i c e ( i n t data ) { cout<< Twice : << data 2 << e n d l ; }

s s in And, if we call this function as: P r i n t T w i c e ( 4. 5 5 4 7 ) ; It would instantiate another function as: void P r i n t T w i c e ( double data ) { cout<< Twice : << data 2 << e n d l ; }

s s in If you call PrintTwice function with int and double types, two instances of this function would be generated by the compiler: void P r i n t T w i c e ( i n t data ) {... } void P r i n t T w i c e ( double data ) {... } The code is duplicated, but these two overloads are instantiated by the compiler and not by the programmer. Benefit is that you need not to do copy-pasting the same code, or to manually maintain the code for different data-types, or to write up a new overload for new data-type that arrives later. Code size (at binary/assembly level) would increase, since there are now two function definitions. Effectively, for N number of data-types actually called in main, N instances of same function (i.e. overloaded functions) would be created.

Operators are functions too s s in When templating a function, you must insure that any operator used in the body of the templated function is implemented (supported) for the types you may pass in.