Calculate factorial using template compilation

Source: Internet
Author: User

//////////////////////////////////////// /// // C ++ templates meta programming template <bool, typename T1, typename T2> struct If {typedef T1 type ;}; template <typename T1, typename T2> struct If <false, typename T1, typename T2 >{ typedef T2 type ;}; template <int n> struct Factorial_exception {enum {Value =-1 };}; template <int n> struct _ Factorial {enum {Value = n * _ Factorial <n-1> :: Value };}; template <> struct _ Factorial <0 >{ enum {Value = 1 };}; // final result template <int n> struct Factorial {enum {Value = If <n <1, Factorial_exception <n>/* When the Value is less than 1, the Factorial is-1 */, _ Factorial <n >:: type: Value };}; example: int I = Factorial <-2 >:: Value; // The compiled assembly code for this statement is mov dword ptr [I], 0 FFFFFFFFh amazing?

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.