$\require{cancel}$
Intro to Templates
- This is chapter 12, you should read it.
- We discuss templates
- These are plans for implementing classes and functions.
- This is the way c++ supports generic programming.
- Generic programming allows to write code in a to-be-sepecified-later datatype
- The template is a blue-print for the code.
- When the compiler detects that we need new code based on the template, it will write it for us.
- We will just be covering the basics in the next few days.
- There is more
- And it is changing.
- The general idea that templates allow us to parameterize classes and functions for types just like we do for data values.
- Warning: we will be putting what looks like code in .h files.
- This is NOT the case.
- If "code" is enclosed in a template structure, it is not code.
- It is a blueprint.
- The compiler will use this to generate the actual code.
- Basic syntax:
-
template < typename T> declaration;
-
template < class T> declaration;
-
template < typename T, typename Q> declaration;
- The
T
will then become a stand-in for a type.
- I am going to skip ahead to 447 for function templates.
- The base example is usually the
min
function
- This take two items of the same type and returns the smallest.
- This assumes that the < operator is defined on this type.
- There is code in development to control this, but we will just assume it to be true for our discussions.
- Examples in MinT.h
- By the way, there is an algorithm section of the standard library
- Many of the algorithms you need will be there.
- Most are templated.
-
min
is there.
- Look at the man page for min
- We will look at this later.