Key Points
Templates
-
A template is a recipe for generating code that works with different types.
- A template has template parameters that can be filled in with various types.
- Declare a template with, for example,
template <typename T>
(whereT
is the parameter) - You can have function templates and class templates.
-
A template cannot be compiled on its own.
- The actual instructions would differ for different types.
- So a template must be compiled along with code that uses it (provides specific template arguments).
-
Typical file structure for templates.
- A source file that uses the template includes
, whichmy-templated-thing .hpp- Contains traditional “header-file” content (declarations, etc.)
- And—at the bottom of the file—
#include
s
, whichmy-templated-thing -private.hpp- Contains traditional “source-file” content (definitions, etc.)
- There is no
file.my-templated-thing .cpp
- A source file that uses the template includes
Type Conversion
- When choosing which function to call for overloading, for each argument an exact match on the type is best, then a template-based argument, then type conversion.
- Type conversion between classes is possible, but only if one of the classes specifies how. There are two ways to do it:
- The “target” class can define conversion by creating a single-parameter constructor and/or creating a specialized version of the assignment operator.
- The “source” class can define conversion by creating a type-casting operator.
- If you don't want a single-parameter constructor or type-casting operator to be used for implicit conversion, you should use the
explicit
keyword. - There are limits to how much conversion the compiler will do:
- It will only perform conversion once; it won't do a “chain” of conversions.
- It will only perform conversion for parameters to a function; you can't apply conversion to a value that you're calling a member function on.
(When logged in, completion status appears here.)