Listing 10
// Using For<> to calculate the square root
template<int number, int low_ = 0 , int high_ = number>
struct sqrt_state
{
enum { num = number }; // doesn't change
enum { low = low_ };
enum { high = high_ };
};
template<typename state>
struct sqrt_cond
{
enum { result = state::low < state::high };
};
template <typename state>
struct sqrt_incr
{
typedef state result ; // state is left unchanged
};
// slice the range into two halves and decide in which half
// to continue search
template<typename state>
struct sqrt_body
{
enum { mid = state::low + (state::high - state::low) /2 };
enum { in_first_half = mid * mid >= state::num } ;
typedef sqrt_state<state::num, state::low, mid> first_half;
typedef sqrt_state<state::num, mid+1, state::high> sec_half;
typedef typename If_else< in_first_half, first_half,
sec_half >::result result;
};
// compute square root of N
template <int N>
struct sqroot
{
enum { result = For<sqrt_cond, sqrt_incr,
sqrt_body, sqrt_state<N> >::result::low } ;
};
cout << sqroot<16>::result ;