This post is simply translated from the one I wrote on CSDN: https://blog.csdn.net/noahzuo/article/details/51133525
Introduction
Algorithms can be templated if input parameters can be determined during compilation. As a result, compiler can do the optimization work for us during handling templates.
Fibonacci Sequence
We all know how to write fibonacci in a traditional but inefficient way:
1 | unsigned int fib(unsigned int n) { |
We can use template programming to optimize it:
1 | template <unsigned int N> |
It needs to be mentioned that a template function is a enumerated value that is calculated during compilation instead of a real function.
For the compiler, it runs like:
1 | fib (4) |
Thus this value is solved during compilation, we can save the performance for runtime.
Factorial
The traditional way is like:
1 | unsigned int fact (n ) |
But we can use template programming to optimize it:
1 | template < unsigned int N > |
So if n
can be given during compilation stage, fact(n)
can be solved right away.
Drawback
Of course something needs to be mentioned:
- We might have to suffer from longer compiling time.
- It might be harder to read or debug the relevant code.