When using the template, remember that typename and class are used as parameters. It's amazing to see it again.
Template parameters are not limited to types. You can use built-in types in the compiler.
The template tells the compiler that some definitions contain one or more unknown quantities (constants or types ).CodeThe compiler must replace these values.
TMP's "Hello World"ProgramCalculate a factorial during compilation. It is not an exciting program. However, even if it is not "Hello World", it also helps to get started with the language. TMP factorial calculation demonstrates a loop through recursive template instantiation (recursive template instantiation. It also demonstrates a way to create and use variables in TMP. See:
Template <unsigned n> // general case: the value
Struct factorial // factorial <n> is n times the value
{// Of factorial <n-1>
Enum {value = N * factorial <n-1 >:: value };
};
Template <> // special case: the value
Struct factorial <0 >{// factorial <0> is 1
Enum {value = 1 };
};
This template metaprogram (template metaprogram) (actually only a separate template metafunction (template mettorial) factorial) is provided. You can obtain factorial (n) by referencing factorial <n >:: value).
The cyclic part of the code appears in template instantiation (template instantiation) factorial <n> references template instantiation (template instantiation) factorial <n-1>, in this way, it will continuously instance new types of factorial <n-1> and obtain the value values of each type to multiply. Because it is an Enum constant, therefore, the value of each value is calculated during compilation.
All correct recursion (recursion) has an exit. Here, it is template specialization (template-specific) factorial <0>.
Each instantiation (Instance) of the factorial template is a struct, and each struct has a corresponding factorial value.