The template meta-programming of C ++ is a relatively advanced technology in C ++. You can use some Template Techniques to implement computation during compilation, A common example is to find a sum and a Fibonacci series. To be honest, I have never used these technologies in my project. When I talked to my colleagues about C ++, Java, and C # templates yesterday, I suddenly thought of this and tried it, write a sum:
# Include <iostream> Using Namespace STD; Template < Int N> Class Sum { Public : Enum {Value = N + sum <n- 1 > : Value };}; Template <>Class Sum < 0 > { Public : Enum {Value = 0 };}; Int Main () {cout <Sum <100>: value < Endl ;}
This is nothing more than recursion. Just like writing a common recursive function, write the recursion rule (template function) and the recursion end condition (template function is special ), but when I change the input value to 501 (gcc4.1 ?), The compiler reports an error. It seems that the compiler has a limit on Template recursion from the error information. Later, I tried it on GCC 4.6. The maximum value is 1024, and the error information is reliable:
Sum. CPP: 9: 14: Error: template instantiation depth exceeds maximum of 1024 (use-ftemplate-depth = to increase the maximum) instantiating 'class sum <1> 'sum. CPP: 9: 14: recursively instantiated from 'sum <1024> 'sum. CPP: 9: 14: instantiated from 'sum <1025> 'sum. CPP: 22: 22: instantiated from here
Use-ftemplate-depth. Of course, it can increase, but after all, the system resources are limited, and you cannot increase them without restraint. The compiler has the following restrictions:
- Resource-every recursion is saved, and the memory will crash sooner or later
- Some poorly written template classes may be infinite recursion-the compiler will be there without limits
For vc9 in windows, the default limit is 499 (up to 500). After checking the compiler parameters, the maximum depth of vc9 is not found.
This is all done, but some people have proposed a good way to use metaprogramming to solve the sum (of course not using n (n + 1)/2). It is very inspiring:
# Include <iostream> Using Namespace STD; Template <Unsigned start, unsigned end>Struct Adder { Static Unsigned Const Middle = (start + end )/ 2 ; Static Unsigned Const Value = adder <start, middle >:: value + adder <middle + 1 , End> : Value;}; Template <Unsigned end> Struct Adder <End, end> { Static Unsigned Const Value = End ;}; Int Main () {cout <Adder < 1 , 1000 > : Value ;}
UnderstandingAlgorithmLet's take a look at it and we will know that this is a divide-and-conquer method. Every recursion involves two forks, so we can reduce the total number from N to lgn, greatly improving!
In fact, the so-called computation during the compilation period is the runtime period for the compiler, so it is better to write recursive algorithms, improve recursion and use sub-governance, and write commonCodeThe same is true.