190 likes | 199 Views
Templates. Generic Programming. The Issue. Want function to find the larger of two values. Up Until Now. Need multiple versions: int largest(int num1, int num2) { //return largest } double largest(double num1, double num2) { //return largest }
E N D
Templates Generic Programming
The Issue • Want function to find the larger of two values
Up Until Now • Need multiple versions: int largest(int num1, int num2) { //return largest}double largest(double num1, double num2) { //return largest} Person largest(const Person& p1, const Person& p2) { //return largest}
Templates • Templated Functions • Specify way to build a function • Applies to any data type
Template Declaration • template<class/typenameT> • class/typename interchangeable • T is a type parameter – can be anything • Can have multiple type parameters • https://www.tutorialspoint.com/compile_cpp_online.php
Exe 1 • Go to https://www.tutorialspoint.com/compile_cpp_online.php • Implement the Min method following the idea of Slide #4 • Show me the output
Type Parameter • Type parameter used to code template: • Whatever T is… • We return one • We take two as parameters
Instantiation • Template instantiated when needed at compile time • New version of code createdfor each type templateapplied to
Template Including • Template functionsmust have full code in.h file • Needed at compile timefor instantiation • Don’t have to worry aboutmultiple versions
Templates • All T's must be same type • No conversions done
Templates • All T's must be same type • No conversions done • Can force type
Exe 2 • Try to call Max of Exe 1 with f1 and j • What is the key step to make it to work?
Operators & Members • Template can assume any operators/members it wants • Compile error if type doesn't support
Non Templated Params • Can have normal parameters in template function
Templated Variables • Can use template type as local variable type
Templated Class • Class can be template • Type of variable includes instantiation type:
Templated Class Functions • Function definitions must be template • Scope resolution must include template
Templates of Templates • Template can instantiate on templated type:
Multiple Types • Template can have multiple types: