First taste of "metaprogramming" (C ++ description)

Source: Internet
Author: User

Let's look at two programs for calculating the Fibonacci number:

(1) runtime

#include <iostream>using namespace std;const int N = 45;int Fib(unsigned n){if (0 == n) return 0;if (1 == n) return 1;return Fib(n - 1) + Fib(n - 2);}int main(int argc, char **argv){cout << Fib(N) << endl;return 0;}

(2) compilation phase

#include <iostream>using namespace std;const int N = 45;template<unsigned N>struct Fib {enum {RESULT = Fib<N - 1>::RESULT + Fib<N - 2>::RESULT};};template<>struct Fib<1> {enum {RESULT = 1};};template<>struct Fib<0> {enum {RESULT = 0};};int main(int argc, char **argv){cout << Fib<N>::RESULT << endl;return 0;}

Core Assembly Code

013013C8 68 82 3F A5 43       push        43A53F82h

43a53f82h (hexadecimal) is exactly fib (45), and results have been obtained during compilation.

The first program is the time complexity of the exponential model, which is very slow. The second program looks similar, but it is recursively completed during compilation, and compilation + running is almost time-consuming.

I have some doubts,

1. How to evaluate the time complexity of the second program? Why can it "earn" efficiency? This reminds me of the difference between the "counting sorting" and the comparison-based sorting. Therefore, in some cases, it will bring revolutionary efficiency!

Think about some people. If you can't keep thinking, it's really hard to improve. If you look at it from another angle, it may be a world.

2. How can I use the metaprogramming Technology on ACM?

References: http://www.doc88.com/p-418478822377.html

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.