I've been playing with template recursion to compute constants at compile time. I have successfully implemented a factorial based one. I was trying to write one that computed e.
e is defined as 1 + 1/1! + 1/2! + 1/3! + 1/n!
So I tried
namespace KS
{
namespace Math
{
template <unsigned int Limit, typename T>
struct E
{
//static const T result;
};
template <unsigned int Limit>
struct E <Limit, float>
{
static const float result;
};
template <>
const float E <0, float>::result = 1.0f;
// Assume that KS::Math::Factoral does return a succesful factorial, which tests show that it does
template <unsigned int Limit>
const float E <Limit, float>::result = ((KS::Math::E<(Limit - 1), float>::result) + (1.0f / KS::Math::Factorial<(Limit)>::result));
}
}
// Here is my test code
std::cout << KS::Math::E<0, float>::result << std::endl;
std::cout << KS::Math::E<1, float>::result << std::endl;
std::cout << KS::Math::E<2, float>::result << std::endl;
std::cout << KS::Math::E<6, float>::result << std::endl;
Here is the result of the code.
1 (This would be doing 1 which would be a straight constant, so corect)
2 (This should be 1/1! + 1, so again correct. Note that if I didn't actually put the std::cout << KS::Math::E<0, float>::result << std::endl; before it, it resolves to just 1, which would just be 1/1!)
2.5 (This should be 1/2! + 1/1! + 1, so again correct. Note that if I didn't actually put the std::cout << KS::Math::E<0, float>::result << std::endl; & std::cout << KS::Math::E<1, float>::result << std::endl; before it, it resolves to just 0.5, which would just be 1/2!)
0.00138889 (This is just resolving to 1/6!, instead of doing any of the recursion, as the above 3 show, I would guess that if I manually do E<3>, E<4>, & E<5> before it, they would all resolve correctly.
So what it looks like it is doing is if a E<some number, float> is on its own, it just does the 1 / some number! math. If all of the neccessary calculations are predefined before it is needed, it is successfully solving for it. Is there just a problem with my logic somewhere?
Note: You can't go higher than E<12, float>, because the factorial would overflow an int.
[edit]
This is all purely academic. So please, do not recommend using someone else's libraries ala boost or just using a constant.
[/edit]