Game Development Reference
In-Depth Information
The first two lines of Listing 20-3 will compile without issue. The compiler can work out the value of
the result from the
sin
function at compile time and store the values in the variables. The
constexpr
variable inside the
ConstFunction
, however will result in a compile error. GCC gives the following
output message:
error: 'value' is not a constant expression
. This happens because the compiler
cannot guarantee that the method will not be passed a value that it cannot determine at compile time.
assert
Versus
static_assert
The
assert
and
static_assert
methods have the same runtime versus compile time distinction as
const
and
constexpr
. An
assert
is used to halt your program's execution if you pass in
false
at
runtime. Listing 20-4 shows a use of
assert
.
Listing 20-4.
assert
#include <cassert>
int main()
{
assert(2 == 3);
}
The
2 == 3
expression will result in
false
being passed to the
assert
. This will cause the code
execution to stop in your debugger and allow you to continue. A
static_assert
on the other hand
causes the compiler to throw an error. Listing 20-5 shows a
static_assert
.
Listing 20-5.
static_assert
#include <cassert>
int main()
{
static_assert(2 == 3, "Two does not equal three");
}
When you compile this code using GCC you should see the following error:
error: static assertion
failed: Two does not equal three
. This is the purpose of the string being passed to the
static_assert
: It is printed out as part of your compile error. These type of asserts are very useful
when trying some template metaprogramming.
Summary
This chapter has shown you the very basics of how to create templates in your own code, including
the difference between compile time and runtime evaluation through a look at the difference between
const
and
constexpr
, and
assert
and
static_assert
. You've seen a basic use of the
template
and
typename
keywords and how these are used to create type abstractions in your code.
The remaining chapter in this part of the topic covers how you can use templates in the Text
Adventure game in the form of template function, template classes, and finally an example of how
template metaprogramming can be used to calculate an SDBM hash at compile time.