I am experimenting with Template metaprogramming (TMP) and I was working on a "basic" TMP program like factorial calculation.
The code is this:
1 2 3 4 5 6 7 8 9 10
template<unsigned n> // general case: the value of
struct Factorial { // Factorial<n> is n times the value
// of Factorial<n-1>
enum { value = n * Factorial<n-1>::value };
};
template<> // special case: the value of
struct Factorial<0> { // Factorial<0> is 1
enum { value = 1 };
};
(I took it form "effective C++"). Code works fine but if I attempt to instantiated with a unsigned n unknown during compilation (e.g. one that it will be read on runtime) like this Factorial<n>::value an error occurred. Is there a way to bypass this somehow. I mean it's useful this way but not always as it's obvious.
This seems like a poor demonstration on how or when to use templates (although it seems like a unique way to use enum). Have you looked at the tutorial on this site? It's free. I see a specilized template in Lines 1 - 5 and a default template declaration in Lines 7 - 10, but I do NOT see any point where it is practicle to use a template in this post. Are you sure you copied this correctly? I think your confusion is simply due to this awkward example.
I copied it correctly and I mentioned before this works fine (expect for the fact that I cannot use a variable instead of constant like R0mai mentioned). I don't know a lot on templates (just a few examples I have used). Maybe it's not the most practical example I needed an opinion if I could bypass the const necessity by compile time. This example was demonstrated as an example of recursion in TMP. I will check the tutorial also.
The entire point of TMP is to calculate non-trivial values at compile-time (well, among other things).
If you need to calculate values based on user input, use regular functions.