Game Development Reference
In-Depth Information
The class can use the T type in place of a standard type. The compiler will replace the T anywhere it
is used with the type supplied when the template is specialized. Listing 20-2 shows how this class
template can be specialized.
Listing 20-2. Specializing a Template
int value = 1;
Template<int> pointer(&value);
When we compile our program the compiler will automatically create a class for the Template<int>
type that replaces T with int .
The remainder of this chapter looks at the way we can specify constant values to be used by the
template compiler and look at the difference between a runtime and compile time assert.
const Versus constexpr
C++11 introduced the constexpr keyword to coexist with the const keyword. You've already seen
const used in this topic. In those instances we used const to create variables that were unable to
be changed by the program after they were defined. These variables are runtime variables. We can
have constants defined inside local variables using values passed from parameters. Parameters
themselves can even be constant and in these cases there is no way for the compiler to know
whether the values the variables contain are literal constant values or values determined at runtime.
The constexpr keyword has been added to aid in this distinction. If you create a variable using
constexpr the compiler will throw a compiler error if it cannot determine the value of the variable at
compile time.
Note Unfortunately, at the time of writing, Microsoft has not yet added support in their latest compiler
included with Visual Studio 2013.
Listing 20-3 shows two scenarios where const and constexpr will provide different results.
Listing 20-3. const Versus constexpr
const double constValue = sin(0.5);
constexpr double constexprValue = sin(0.5);
void ConstFunction(double value)
{
const double constValue = value;
constexpr double constexprValue = value;
}
 
 
Search WWH ::




Custom Search