160 likes | 273 Views
Standard Template Libraries . Anjali Agrawal Prashant Kirtane. Topics to be covered !. Templates Overview of STLs How to use STLs. Templates Why ? . int maximal(int a, int b) { if (a > b) return a; else return b; }
E N D
Standard Template Libraries Anjali Agrawal Prashant Kirtane
Topics to be covered ! • Templates • Overview of STLs • How to use STLs
Templates Why ? int maximal(int a, int b) { if (a > b) return a; else return b; } What if we need a function to return the larger of two doubles, two floats, and two chars in the same program ?
Better Solution ! template <class T> T maximal(T a, T b) { if (a > b) return a; else return b;}
Defining Templates ! • generic structures that can be instantiated for specific data types as needed. • Instantiation is the act of creating a specific type from a template.
Motivation ... • Certain data structures, which have behavior that is independent of the kind of information they contain. • E.g. • stacks - behaviors push, pop, top • queues - behaviors insert, remove, front
Using Templates in c++ ! • C++ allows the creation of two kinds of templates • Class templates • Function templates
Class Templates Definition • specify a generic class that can be instantiated to create actual classes. • E.g. template <class T> class cArray { public : cArray(); };
Class Templates Instantiation • A class template is instantiated when a variable or type is created using the generic class name. • E.g. cArray<int> aIntArray; cArray<char> aCharArray;
Lets understand the difference ! • Instantiation of the class E.g. template <class T> class cArray{ …… }; cArray<int> aIntArray; typedef cArray<int> aIntArray;
Function Templates Definition • Specify a generic function that can be instantiated for specific argument types to create actual functions. • E.g. template < class T > int someFunction(T arg) { ... …}
Function Templates Instantiation • A function template is instantiated when a call to the function occurs with parameters of a specific type. • E.g. someFunction(42); Creates a new function someFunction(int) in which all occurrences of T are replaced by int, and calls this function.
Lets understand the basics ! template <class T> T tMaxima(T a, T b) { ….. } tMaxima(4, 3); tMaxima(9, 8 ); • If the same template is used more than once with the same types of parameter in same compilation, it is instantiated only once.
Template Parameters • Templates can have any number of parameters. • The parameters can be either types or values or objects. • E.g. Template <int iSize, class T, cFoo ob> class cSomeClass{ … };
Template Parameters .. Instantiation • Instantiation of templates with parameters E.g. cSomeClass<127, char,myFoo> aChrClass;
Function Template Arguments • E.g. Template <class T, int iSize> T tMaxSize(T a, T b) { …… }; tMaxSize<int, 5> (7, 4);