Functional programming and C + + template element programming

Source: Internet
Author: User

Let's take a look at an example:

#include <stdio.h>
template <int depth>
class Fibnacci
{
public:
    static const int value = Fibnacci<depth-1>::value + Fibnacci<depth-2>::value;
};

template <>
class Fibnacci<0>
{
public:
    static const int value = 0;
};

template <>
class Fibnacci<1>
{
public:
    static const int value = 1;
};

template <int depth>
void printFibnacci()
{
    printFibnacci<depth-1>();
    wprintf(L"%d\n", Fibnacci<depth>::value);
}

template <>
void printFibnacci<0>()
{
    wprintf(L"%d\n", Fibnacci<0>::value);
}

int main()
{
    printFibnacci<8>();
    return 0;
}

Fibnacci series, I believe it is a programmer can write out, the point is, this fibnacci sequence of calculation is complete at compile time! The following print is also true, and when you make a large parameter, the runtime will not change, but you will spend a long time in the compile phase.

If you've heard of some template metaprogramming, you'll know that "C + + templates are Turing complete." How is the template element Turing complete? The answer is that the template element is the same as the functional principle.

The essence of a template is defined and replaced, and the essence of a lambda function is also defined and replaced, where the substitution actually conforms to the lambda calculus Theory in Mathematics:

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.