- [Instructor] C++ templates are marvelously simple
and powerful.
This is the C++ feature that supports generic programming.
Generic programming refers to code that works independent
of type while C++ is a strongly typed language,
there's still great benefit in being able to write functions
and classes that are type agnostic,
that is, they operate on objects without concern
for the type of these objects.
Because C++ supports defining your own types through classes
and operator overloading,
it is possible to do a great deal of generic programming
in templates, while leaving the implementation details
to the classes and operators.
Template declarations look just like normal function
or class declarations with one distinction.
They are preceded by the template keyword,
and a set of type identifiers.
These type identifiers are used as placeholders
by the template code to be replaced
during compilation with actual types.
When a function or class is used from a template,
the compiler generates a specialization specifically suited
to the types identified in the instantiation.
This specialization is generated at compile time,
and one specialization is created for each combination
of data types for each template.
Templates are widely used in the C++ standard library,
which is why parts of the library are commonly called
the standard template library.
The generic nature of templates makes them a perfect fit
for use with container classes.
Template programming is not entirely without its downsides,
there are some issues you'll need to be aware of.
Because the compiler must generate specializations
for every type context of a template,
the amount of code to support that template
can grow rapidly with use.
Compilers tend to have a difficult time
generating sensible error messages with templates,
so debugging can be challenging.
Because templates tend to live in header files,
changes to code with templates can lead to recompilation
of larger portions of your code
than would otherwise be necessary.
C++ templates are a powerful feature
that is also simple to implement and support.
They have great advantages
over generic programming solutions,
including preprocessor macros
and they're widely used to implement containers
and other generic objects in the C++ standard library.
This chapter will cover the fundamentals of using templates
and functions and classes.
For a more detailed discussion,
please see the companion course C++ templates and the STL.