Game Development Reference
In-Depth Information
template <>
struct SDBMCalculator<1>
{
static inline int Calculate(const char* const stringToHash, int& value)
{
return stringToHash[0];
}
};
This code is going to be a little tricky for new C++ programmers to get their head around. Listing 21-19
shows how this code would be used in your code.
Listing 21-19. Using the SDBMCalculator Template Metaprogram
constexpr int QuitEvent = SDBMCalculator<9>::CalculateValue("QuitEvent");
The template metaprogram is passed the length of the string as its template parameter and the string
to hash as a function parameter. The static CalculateValue function is the function that is called.
This function then calls the static Calculate method in the SDBMCalculator struct . You can see
that the Calculate method calls itself. This is the very nature of template metaprogramming: The
programs generally consist of recursive function calls. The Calculate method calls Calculate on an
SDBMCalculator template, which is passed stringLength - 1 as its parameter.
Our QuitEvent string has a length of 9 so the template metaprogram will recurse down until Calculate
can hit the terminating condition. You can see the terminating condition in the specialized version
of the struct . This struct doesn't have any template parameters, but its Calculate function has a
hard-coded parameter of 1 . This specialized version of the function does not call any other version of
Calculate so the calls begin to unwind at this point. If we were to print out the character and value
after each step, the output would be:
Q
81
u
5313636
i
676857093
t
-223462225
E
-175116458
v
1572988576
e
-111689275
Search WWH ::




Custom Search