C + + supplements--template meta-programming

Source: Internet
Author: User

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

    • CCPP Blog Directory



C + + supplements--template meta-programming

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.