C + + supplements--template meta-programming
Preface
The template element is used for recursive acceleration, which changes the run-time function call to the compile time for code expansion, similar to an inline function. Here is an example: the Fibonacci sequence nth solution.
template meta-programming
#include <iostream> #include <ctime>using namespace std;//recursive int fib (int n) {if (n < 0) return 0;if (n = = 1 | | n = = 2) return 1;return fib (n-1) + fib (n-2);} Template meta Template<int n>struct data{enum{res = data<n-1>::res + data<n-2>::res};}; Template<>struct data<1>{enum{res = 1}; Template<>struct data<2>{enum{res = 1}; int main () {cout << "****** template metaprogramming ***by david***" << endl;time_t start, End;start = Clock (); cout << fib (40) << endl;end = Clock (), cout << "recursive time consuming" << end-start << "MS" << Endl;start = Clock (); Cout & lt;< data<40>::res << endl;end = Clock (); cout << "Template meta-method time-consuming" << end-start << "MS" << Endl;cin.get (); return 0;}
Run
Summary:
Recursive method takes a long time. The runtime of the template element method is problematic, and you can see the results when you move the mouse to data<40>::res on vs.
Directory of this column
- C + + Supplements directory
Directory of all content
C + + supplements--template meta-programming