2.1Use enum to do numerical calculation
The following two articles describe template metaprogramming, an enum being the most important basic tool http://www.codeproject.com/Articles/3743/ A-gentle-introduction-to-template-metaprogramming https://www10.informatik.uni-erlangen.de/~pflaum/pflaum/ Proseminar/meta-art.html
Therefore, the following conclusions can be attained:
- The value of the enum is computed by the compiler at compile time
- Template-specific and recursive algorithms allow the compiler to recursively generate a series of class when calculating the enum value.
Here is a simple example, a code that asks for the factorial of N:
#include <iostream>template<int n>class factorial {public: enum {RESULT = N * factorial<n-1>::res ULT};}; Template<>class factorial<1> {public: enum {RESULT = 1};}; int main (int argc, char * * argv) { try { std::cout << factorial<4>::result << Std::endl; } c Atch (std::exception const& e) { std::cerr << e.what () << Std::endl; }}
The recursive algorithm allows the compiler to generate a series of factorial classes: Factorial<1> factorial<2> factorial<3> and factorial<4>. These generated classes cause the compiled program to become larger and the compilation period to become longer, but the runtime becomes very fast. Because the runtime has no recursion, the constants are directly obtained and output.
C + + template meta-programming two: Using enum to do numerical calculation