Game Development Reference
In-Depth Information
Chapter
20
Template Programming
Parts 1 and 2 of this topic introduced you to concepts and features of the C++ programming
language that allow the procedural programming paradigm and the object-oriented programming
paradigm. C++ provides functions and control flow statements that allow you to break your
programs down into reusable blocks and it provides classes that allow you to encapsulate your data
and bundle it with methods that act on that data. C++ also supports a third programming paradigm,
generic programming.
Generic programming is conceptually more complicated than the procedural and object-oriented
programming paradigms. You can think of generic programming in C++ as programming with types.
You've seen examples of this in the previous part of this topic when you saw how to specialize STL
containers. The STL containers are
generic
in that they do not know which type they are until the
code is compiled. When you specialize a template, you are required to pass the types as arguments.
This process creates a new type;
vector<int>
is a completely different type to
vector<char>
.
Templates were created to provide this type abstraction in programs. After templates were
implemented, programmers started to discover that templates could do much, much more than
just abstract out types. They discovered that the template compiler could evaluate constant values
and compile new constant values. This has given rise to another element to template programming
known as
template metaprogramming.
This chapter gives a brief introduction to template compilation by discussing the difference
between compile time and runtime evaluation, the difference between
const
and
constexpr
, and the
difference between
assert
and
static_assert
.
Compile Versus Runtime Time Compilation
Compilers are complex pieces of software that are capable of turning your source code into
instructions that can be consumed by a processor. During the compilation process, they are also
capable of carrying out other tasks, including preprocessing and optimization. The compiler is
also responsible for processing templates. Templates are generic and therefore the source code
itself cannot resolve the types in use in the template code. The compiler could try to instantiate a
version of the template for every single type and class in your program, but this would likely be very
201