Download presentation
Presentation is loading. Please wait.
1
Templates Generic Programming
2
The Issue Want function to find the larger of two values
3
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 }
4
Templates Templated Functions Specify way to build a function
Applies to any data type
5
Template Declaration template<class/typename T>
class/typename interchangeable T is a type parameter – can be anything Can have multiple type parameters
6
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
7
Type Parameter Type parameter used to code template: Whatever T is…
We return one We take two as parameters
8
Instantiation Template instantiated when needed at compile time
New version of code created for each type template applied to
9
Template Including Template functions must have full code in .h file
Needed at compile time for instantiation Don’t have to worry about multiple versions
10
Templates All T's must be same type No conversions done
11
Templates All T's must be same type No conversions done Can force type
12
Exe 2 Try to call Max of Exe 1 with f1 and j
What is the key step to make it to work?
13
Operators & Members Template can assume any operators/members it wants
Compile error if type doesn't support
14
Non Templated Params Can have normal parameters in template function
15
Templated Variables Can use template type as local variable type
16
Templated Class Class can be template
Type of variable includes instantiation type:
17
Templated Class Functions
Function definitions must be template Scope resolution must include template
18
Templates of Templates
Template can instantiate on templated type:
19
Multiple Types Template can have multiple types:
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.