C++ Templates. David Camp

Similar documents
Chapter 12 - Templates

Templates (again) Professor Hugh C. Lauer CS-2303, System Programming Concepts

Laboratorio di Tecnologie dell'informazione

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Cpt S 122 Data Structures. Templates

IS 0020 Program Design and Software Tools

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

Programmazione. Prof. Marco Bertini

September 19,

Chapter 11. Abstract Data Types and Encapsulation Concepts

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Cpt S 122 Data Structures. Templatized Stack

! A data type for which: ! In fact, an ADT may be implemented by various. ! Examples:

C and C++ 7. Exceptions Templates. Alan Mycroft

(heavily based on last year s notes (Andrew Moore) with thanks to Alastair R. Beresford. 7. Exceptions Templates 2/1. Throwing exceptions 14 }

Exceptions. CandC++ 7. Exceptions Templates. Throwing exceptions. Conveying information

CS 247: Software Engineering Principles. C++ Templates. Reading: Eckel, Vol. 2 Ch. 5 Templates in Depth. U Waterloo CS247 (Spring 2017) p.

Exercise 6.2 A generic container class

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

Short Notes of CS201

Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü ++ Bilişim Enstitüsü

C++ Exception Handling 1

CS201 - Introduction to Programming Glossary By

An introduction to. Templates. Generic Programming. Good old C. Metaprogramming 4/13/2017

Stacks. Gaddis 18.1, Molly A. O'Neil CS 2308 :: Spring 2016

COMP6771 Advanced C++ Programming

Overview. 1. Expression Value Categories 2. Rvalue References 3. Templates 4. Miscellaneous Hilarity 2/43

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

EL2310 Scientific Programming

eingebetteter Systeme

! A data type for which: ! An ADT may be implemented using various. ! Examples:

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

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

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

CPSC 427: Object-Oriented Programming

Bruce Merry. IOI Training Dec 2013

Introduction to the Stack. Stacks and Queues. Stack Operations. Stack illustrated. elements of the same type. Week 9. Gaddis: Chapter 18

CSE 303: Concepts and Tools for Software Development

Object-Oriented Programming for Scientific Computing

CS250 Final Review Questions

Object Oriented Programming COP3330 / CGS5409

CSCE 110 PROGRAMMING FUNDAMENTALS

Implementing Subprograms

Ch. 18: ADTs: Stacks and Queues. Abstract Data Type

Templates and Vectors

Part X. Advanced C ++

Chapter 7: Stacks. Exercises 7.2

And Even More and More C++ Fundamentals of Computer Science

EL2310 Scientific Programming

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CMSC 4023 Chapter 11

IV. Stacks. A. Introduction 1. Consider the 4 problems on pp (1) Model the discard pile in a card game. (2) Model a railroad switching yard

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

! Operators such as =, +, <, can be defined to. ! The function names are operator followed by the. ! Otherwise they are like normal member functions:

ADTs: Stacks and Queues

Today s lecture. CS 314 fall 01 C++ 1, page 1

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

CS 61B, Spring 1996 Midterm #1 Professor M. Clancy

Exception Namespaces C Interoperability Templates. More C++ David Chisnall. March 17, 2011

Comp151. Function Templates & Class Templates

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

COMP6771 Advanced C++ Programming

What will happen if we try to compile, link and run this program? Do you have any comments to the code?

Time(int h, int m, int s) { hrs = h; mins = m; secs = s; } void set(int h, int m, int s) { hrs = h; mins = m; secs = s; }

COMP 2355 Introduction to Systems Programming

COEN244: Class & function templates

Interview Questions of C++

AN OVERVIEW OF C++ 1

Pointers, Dynamic Data, and Reference Types

Come and join us at WebLyceum

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Review: C++ Basic Concepts. Dr. Yingwu Zhu

Abstract Data Types and Encapsulation Concepts

CS 162, Lecture 25: Exam II Review. 30 May 2018

EL2310 Scientific Programming

CS93SI Handout 04 Spring 2006 Apr Review Answers

Dynamic Data Structures

OBJECT ORIENTED PROGRAMMING USING C++

Generics/Templates. Steven R. Bagley

Introduction to C++ Systems Programming

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Chapter 15 - C++ As A "Better C"

G52CPP C++ Programming Lecture 14. Dr Jason Atkin

05-01 Discussion Notes

Introduction to C++ Templates and Exceptions. C++ Function Templates C++ Class Templates Exception and Exception Handler

C++_ MARKS 40 MIN

Programming, numerics and optimization

CSCI-1200 Computer Science II Fall 2006 Lecture 23 C++ Inheritance and Polymorphism

Associate Professor Dr. Raed Ibraheem Hamed

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Increases Program Structure which results in greater reliability. Polymorphism

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

CS

l Operators such as =, +, <, can be defined to l The function names are operator followed by the l Otherwise they are like normal member functions:

Chapter 11. Abstract Data Types and Encapsulation Concepts

CS 61B, Spring 1996 Midterm #1 Professor M. Clancy

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Containers: Stack. Jordi Cortadella and Jordi Petit Department of Computer Science

Transcription:

C++ Templates David Camp

C Marcos #define <identifier>(<parameter list>) <replacement token list> #define min(i, j) (((i) < (j))? (i) : (j)) #define max(i, j) (((i) > (j))? (i) : (j)) #define RADTODEG(x) (x * 57.29578) // What is the problem with using this macro RADTODEG(a + b) // = (a + b * 57.29578)

C Marcos #define PRETTY_PRINT(msg) \ printf ("Message: '%s'\n", msg); if (n < 10) PRETTY_PRINT("n is less than 10"); else PRETTY_PRINT("n is at least 10"); error: expected expression before else gcc 4.1.1 Why do we get this error message?

C Macro Problems There are many problems with C macros: There is no way for the compiler to verify that the macro parameters are of compatible types. The macro is expanded without any special type checking. Debugging problems. May only show the macro or may step in but the variables are wrong Cause wrong code to be generated. See more about C Macros at http://en.wikipedia.org/wiki/c_macro

Function Templates template<class T> const T& max( const T& i, const T& j ) return ((i < j)? i : j) ; // use in code cout << max( 3, 7 ); // outputs 7 // Compiler create the following function const int& max( const int& x, const int& y ) return((i < j)? i : j);

Function Templates int main() // calls max<int> (by argument deduction) std::cout << max( 3, 7 ) << std::endl; // calls max<double> (by argument deduction) std::cout << max( 3.0, 7.0 ) << std::endl; // The type is ambiguous, explicitly instantiate max<double> std::cout << max<double>( 3, 7.0 ) << std::endl; return 0;

Function Templates Perform identical operations for each type of data compactly and conveniently Based on the argument types provided in calls to the function, the compiler automatically instantiates separate object code functions to handle each type of call appropriately. STL algorithms are implemented as function templates

Class templates Class Templates Allow type-specific versions of generic classes Format: template <class T> class ClassName // Class Definition Need not use "T", any identifier will work To create an object of the class, type ClassName< type > myobject; Example: Stack< double > doublestack;

Class Templates Functions Template class functions Declared normally, but preceded by template<class T> Generic data in class listed as type T Template class function definition for class Constructor: template<class T> ClassName< T >::ClassName( int size ) // Creates an array of type T myarray = new T[size];

#define DEFAULT_STACK_SIZE 10 template < class T > class Stack public: Stack( int size = DEFAULT_STACK_SIZE ); ~Stack() delete [] stackptr; bool push( const T& pushvalue ); bool pop( T& popvalue ); private: int _size; int _top; T * _stackptr; // default constructor // destructor // push an element onto the stack // pop an element off the stack // # of elements in the stack // location of the top element // pointer to the stack ; bool isempty() const return( top == -1 ); // utility bool isfull() const return( top == size -1 ); // functions template < class T > Stack< T >::Stack( int size ) _size = size > 0? size : DEFAULT_STACK_SIZE; _top = -1; // Stack is initially empty _stackptr = new T[_ size ]; // allocate space for elements

// Push an element T onto the stack // return true if successful, false otherwise template< class T > bool Stack< T >::push( const T &pushvalue ) if(!isfull() ) stackptr[ ++top ] = pushvalue; // place item in Stack return( true ); // push successful return( false );// push unsuccessful // Pop an element off the stack template< class T > bool Stack< T >::pop( T &popvalue ) if(!isempty() ) popvalue = stackptr[ top-- ]; return( true ); return( false ); // remove item from Stack // pop successful // pop unsuccessful

int main() Stack< double > doublestack( 5 ); cout << "Pushing elements onto doublestack" << endl; for(double f = 1.1; doublestack.push( f ) ; f += 1.1 ) // if success true is returned cout << f << ' '; cout << "\nstack is full. Cannot push " << f << "\n\npopping elements from doublestack\n"; while( doublestack.pop( f ) ) // if success true is returned cout << f << ' '; cout << "\nstack is empty. Cannot pop\n"; Stack< int > intstack; cout << "\npushing elements onto intstack\n"; for(int i = 1; intstack.push( i ) ; ++i) // if success true is returned cout << i << ' '; cout << "\nstack is full. Cannot push " << i << "\n\npopping elements from intstack\n"; while( intstack.pop( i ) ) // if success true is returned cout << i << ' '; cout << "\nstack is empty. Cannot pop\n"; return( 0 );

Stack Sample Output Pushing elements onto doublestack 1.1 2.2 3.3 4.4 5.5 Stack is full. Cannot push 6.6 Popping elements from doublestack 5.5 4.4 3.3 2.2 1.1 Stack is empty. Cannot pop Pushing elements onto intstack 1 2 3 4 5 6 7 8 9 10 Stack is full. Cannot push 11 Popping elements from intstack 10 9 8 7 6 5 4 3 2 1 Stack is empty. Cannot pop

Class Templates and Non-type Parameters Can use non-type parameters in templates Default argument Treated as const Example: template< class T, int elements > Stack< double, 100 > mostrecentsalesfigures; Declares object of type Stack< double, 100> This may appear in the class definition: T stackholder[ elements ]; //array to hold stack Creates array at compile time, rather than dynamic allocation at execution time

Templates and Inheritance A class template can be derived from a template class A class template can be derived from a nontemplate class A template class can be derived from a class template A non-template class can be derived from a class template

Templates and friends Friendships allowed between a class template and Global function Member function of another class Entire class friend functions Inside definition of class template X: friend void f1(); f1() a friend function of all template classes friend void f2( X< T > & ); f2( X< int > & ) is a friend function of X< int > only. The same applies for float, double, etc. friend void A::f3(); Member function f3 of class A is a friend of all template classes

Templates and friends friend void C< T >::f4( X< T > & ); C<float>::f4( X< float > & ) is a friend function of class X< float > only friend classes friend class Y; Every member function of class Y is a friend with every template class made from X friend class Z< T >; Class Z< float > a friend of class X< float >, etc.

Template Parameters C++ templates allow one to implement a generic Stack<T> template that has a type parameter T. T can be replaced with actual types. Templates can have any number of parameters. C++ allows you to specify a default template parameter, so the definition could now look like: template Stack <class T = float, int elements = 100>

Template Specialization Template class specialization overrides the template-generated code by providing special definitions for specific types Template class partial specialization generate a specialization of the class for just one parameter

Template Specialization template<> const string& max<string>( const string& s1, const string& s2 ) if( s1.size() > s2.size() ) return( s1 ); return( s2 );

Partial Template Specialization template< class L, class R > L add( L left, R right ) return( left + right ); template< class R > string add( string left, R right ) ostringstream s; s << left << right; return( s.str() );

Template Metaprogramming template < int N > struct Factorial const int value = N * Factorial<N - 1>::value; ; template <> struct Factorial< 0 > const int value = 1; ; template <> struct Factorial< 1 > const int value = 1; ;

Benefits of Templates C++ promotes code reusability. Templates provide a way to re-use source code Templates are type-safe. Because the types that templates act upon are known at compile time, the compiler can perform type checking before errors occur Create a type-safe collection class (for example, a stack) that can operate on data of any type Templates avoid some of the common errors found in code that use macros like function

Drawbacks to Templates Compiler support Poor error messages Code bloat Hard to find errors in Templates Hard to read error messages during compiling