Code:
#include <iostream>
template <int n> int compileTimeInt() {
return n;
}
template <int a, int b> int compileTimeAdd() {
return compileTimeInt<a+b>();
}
int main() {
std::cout << compileTimeAdd<2,5>() << std::endl;
return 0;
}
That forces the compiler to evaulate the sum at compile time. That said, such an optimization is performed by even the worst optimizing compilers.
If you want to see some pretty cool IMHO use of templates for compile time optimization, see this post.
http://www.cprogramming.com/cboard/s...logcombination
I post a recursive solution to a problem, Sorensen posts an iteritive version, it's limited, though, to a certain size). I post a templated version of Sorensen's code that will expand at compile time to fit any size.
The compile time stuff is really interesting. Still, sometimes it's a bit hard to read, and it's also sometimes not the useful. But you have to believe using the compiler itself, and not the executable it produces, to do work is an intriguing concept.