And Exception Handling
Total Page:16
File Type:pdf, Size:1020Kb
• Introduction • Function Overloading Vs. Function Templates • Function Templates • Overloading Function Templates • Class Templates • Class Template And Non-Type Parameters • Template And Inheritance •Template and Friends •Generic Functions •Applying Generic Functions •Generic Classes •Typename and Export Keyword •Power of Templates INTRODUCTION • C++ templates • Allow very ‘general’ definitions for functions and classes • Type names are ‘parameters’ instead of actual types • Precise definition determined at run-time C++ Function Templates • Approaches for functions that implement identical tasks for different data types – Naïve Approach – Function Overloading – Function Template • Instantiating a Function Templates 6 Approach 1: Naïve Approach • Create unique functions with unique names for each combination of data types – Difficult to keep track of multiple function names – lead to programming errors 7 Example void PrintInt( int n ) { cout << "***Debug" << endl; cout << "Value is " << n << endl; } void PrintChar( char ch ) { cout << "***Debug" << endl; cout << "Value is " << ch << endl; } void PrintFloat( float x ) To output the traced values, we { insert: … } PrintInt(sum); void PrintDouble( double d ) { PrintChar(initial); … } PrintFloat(angle); Approach 2: Function Overloading – Review • The use of the same name for different C++ functions, distinguished from each other by their parameter lists • Eliminates the need to come up with many different names for identical tasks. • Reduces the chance of unexpected results caused by using the wrong function name. 9 Example of Function Overloading void Print( int n ) { cout << "***Debug" << endl; cout << "Value is " << n << endl; } void Print( char ch ) { cout << "***Debug" << endl; cout << "Value is " << ch << endl; } To output the traced values, we void Print( float x ) insert: { Print(someInt); Print(someChar); Print(someFloat); } Approach 3: Function Template • A C++ language construct that allows the compiler to generate multiple versions of a function by allowing parameterized data types. FunctionTemplate Template < TemplateParamList > FunctionDefinition TemplateParamDeclaration: placeholder class typeIdentifier typename variableIdentifier 11 Function Template Syntax • Allow ‘swap values’ of any type variables: template<class T> void swapValues(T& var1, T& var2) { T temp; temp = var1; var1 = var2; var2 = temp; } • First line called ‘template prefix’ • Tells compiler what’s coming is ‘template’ • And that T is a type parameter Template Prefix • Recall: template<class T> • In this usage, ‘class’ means ‘type’, or ‘classification’ • Can be confused with other ‘known’ use of word ‘class’! – C++ allows keyword ‘typename’ in place of keyword ‘class’ here – But most use ‘class’ anyway Template Prefix • Again: template<class T> • T can be replaced by any type – Predefined or user-defined (like a C++ class type) • In function definition body: – T used like any other type • Note: can use other than ‘T’, but T is ‘traditional’ usage Calling a Function Template • Consider following call: swapValues(int1, int2); • C++ compiler ‘generates’ function definition for two int parameters using template • Likewise for all other types • Needn’t do anything ‘special’ in call • Required definition automatically generated Instantiating a Function Template • When the compiler instantiates a template, it substitutes the template argument for the template parameter throughout the function template. TemplateFunction Call Function < TemplateArgList > (FunctionArgList) 16 Example of a Function Template Template parameter template<class SomeType> (class, user defined void Print( SomeType val ) type, built-in types) { cout << "***Debug" << endl; cout << "Value is " << val << endl; } Template To output the traced values, we insert: argument Print<int>(sum); Print<char>(initial); Print<float>(angle); Another Function Template • Declaration/prototype: template<class T> void showStuff(int stuff1, T stuff2, T stuff3); • Definition: template<class T> void showStuff(int stuff1, T stuff2, T stuff3) { cout << stuff1 << endl << stuff2 << endl << stuff3 << endl; } showStuff Call • Consider function call: showStuff(2, 3.3, 4.4); • Compiler generates function definition • Replaces T with double • Since second parameter is type double • Displays: 2 3.3 4.4 Function Templates vs. Overloading • Could overload function for char’s: void swapValues(char& var1, char& var2) { char temp; temp = var1; var1 = var2; var2 = temp; } • But notice: code is nearly identical! • Only difference is type used in 3 places Multiple Type Parameters • Can have: template<class T1, class T2> • Not typical • Usually only need one ‘replaceable’ type • Cannot have ‘unused’ template parameters • Each must be ‘used’ in definition • Error otherwise! Another Template Example: passing two parameters template <class T, int size> class Stack {... T buf[size]; non-type parameter }; Stack<int,128> mystack; Summary of Three Approaches Naïve Approach Function Overloading Different Function Definitions Different Function Definitions Different Function Names Same Function Name Template Functions One Function Definition (a function template) Compiler Generates Individual Functions Class Templates • Can also ‘generalize’ classes template<class T> • Can also apply to class definition • All instances of ‘T’ in class definition replaced by type parameter • Just like for function templates! • Once template defined, can declare objects of the class Class Templates Syntax • For class template declaration: template<class T> class_declaration; • For the implementation of the methods outside the class, the syntax is: template<class T> return_type className<T>::methodName(parameter-list){ ……} • For the implementation of the constructors outside the class, the syntax is: template <class T> className<T>:: className(parameter-list){……} Class Template Definition • template<class T> class Pair { public: Pair() { }; Pair(T firstVal, T secondVal); void setFirst(T newVal); void setSecond(T newVal); T getFirst() const; T getSecond() const; private: T first; T second; }; Class Template Definition • template<class T> Pair<T>::Pair(T firstVal, T secondVal) { first = firstVal; second = secondVal; } Class Template Definition template<class T> void Pair<T>::setFirst(T newVal) { first = newVal; } template<class T> void Pair<T>::setSecond(T newVal) { second = newVal; } Class Template Definition template<class T> void Pair<T>::getFirst() const { return first; } template<class T> void Pair<T>::getSecond() const { return second; } Class Template Definition void main() { Pair<int> score; Pair<char> seats; score.setFirst(3); score.setSecond(0); seats.setFirst(‘a’); seats.setSecond(‘b’); int r1 = score.getFirst( ); char r2 = seats.getFirst(); } Member Function Templates • Notice in member function definitions: • Each definition is itself a ‘template’ • Requires template prefix before each definition • Class name before :: is ‘Pair<T>’ • Not just ‘Pair’ Generic programming • Generalize algorithms – Sometimes called “lifting an algorithm” • The aim (for the end user) is – Increased correctness • Through better specification – Greater range of uses • Possibilities for re-use – Better performance • Through wider use of tuned libraries • Unnecessarily slow code will eventually be thrown away • Go from the concrete to the more abstract Templates and Inheritance A class template can be derived from a non-template class A template class can be derived from a class template A non-template class can be derived from a class template Overloading Function Templates • You overload functions when you create functions with the same name but with different argument lists • You can overload function templates, as long as each version of the function takes different arguments, allowing the compiler to distinguish between them 1 A main() Function that Uses the Overloaded invert() Function Template Overloading Function Ex10-3.cpp Templates • Overload the displaySmallest() function template to accept two as well as three arguments 3 Templates and Inheritance A class template can be derived from a non-template class A template class can be derived from a class template A non-template class can be derived from a class template A class template can be derived from a non-template class • For Example : #include<iostream> class base { protected : int x; public : base( ) { } base(int val) { x = val;} }; A class template can be derived from a non-template class template<class T> class derived : public base { T y; public : derived( ) { } derived(T val1, int val2) { base(val2); y = val1; } T add( ) ; }; A class template can be derived from a non-template class template<class T> T derived<T> : : add( ) { return x + y; } int main( ) { derived<int> ob(10,20); cout<<“Addition is : “ <<ob.add( ); return 0; } A template class can be derived from a class template • For Example : #include<iostream> template<class T> class base { protected : T x; public : base( ) { } base(T val) { x = val;} }; A template class can be derived from a class template template<class T> class derived : public base<T> { T y; public : derived( ) { } derived(T val1, T val2) { base<T>::base(val2); y = val1; } T add( ) ; }; A template class can be derived from a class template template<class T> T derived<T> : : add( ) { return x + y; } int main( ) { derived<int> ob(10,20); cout<<“Addition is : “ <<ob.add( ); return 0; } A non-template class can be derived from a class template • For Example : #include<iostream> template<class T> class base { protected : T