I do enjoy a challenge
Here's code that will essentially calculate floor(log10(N)) at compile time.
Code:
#include<iostream>
using namespace std;
// compile time pow()
template<int X, int Y>
struct ctime_pow
{
enum {result = X * ctime_pow<X, Y-1>::result};
};
// specialization for pow(X, 0) to stop recursion
template<int X>
struct ctime_pow<X, 0>
{
enum {result = 1};
};
// recusively calculate X^Potens where X^Potens <= MAX
template<int X, int Potens, int MAX, bool bStop>
struct greatest_pow_imp
{
enum {result = greatest_pow_imp<X,
Potens + 1,
MAX,
(ctime_pow<X, Potens + 1>::result > MAX)>::result};
};
// specialization where bStop is true, "choose" Potens - 1
template<int X, int Potens, int MAX>
struct greatest_pow_imp<X, Potens, MAX, true>
{
enum {result = Potens - 1};
};
// calculate greatest power of X that is <= MAX
template<int X, int MAX>
struct greatest_pow //less than or equal to MAX
{
enum {result = greatest_pow_imp<X, 0, MAX, false>::result};
};
#define TEST(X, MAX) \
cout << "greatest_pow<" #X ", " #MAX ">::result = " \
<< greatest_pow<X, MAX>::result << endl
int main()
{
TEST(10, 0);
TEST(10, 1);
TEST(10, 9);
TEST(10, 10);
TEST(10, 99);
TEST(10, 100);
TEST(10, 999);
TEST(10, 1000);
return 0;
}//main
gg