Presentation is loading. Please wait.

Presentation is loading. Please wait.

Templates Generic Programming.

Similar presentations


Presentation on theme: "Templates Generic Programming."— Presentation transcript:

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(Person p1, 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 Type Parameter Type parameter used to code template: Whatever T is…
We return one We take two as parameters

7 Instantiation Template instantiated when needed at compile time
New version of code created for each type template applied to

8 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

9 Templates All T's must be same type No conversions done

10 Templates All T's must be same type No conversions done Can force type

11 Operators & Members Template can assume any operators/members it wants
Compile error if type doesn't support

12 Non Templated Params Can have normal parameters in template function

13 Templated Variables Can use template type as local variable type

14 Templated Class Class can be template
Type of variable includes instantiation type:

15 Templated Class Functions
Function definitions must be template Scope resolution must include template

16 Templates of Templates
Template can instantiate on templated type:

17 Multiple Types Template can have multiple types:


Download ppt "Templates Generic Programming."

Similar presentations


Ads by Google