-3

been having some issue with a sqrt template function (just want to try, I know < cmath> won't bottleneck anything)

The code below gives the error: too many template arguments

namespace {
    static const size_t ITERATIONS = 10;
}

template <typename T, T N> struct Sqrt {
    static const T value = Sqrt<T, N, 1, ITERATIONS>::value;
};
//Newtons method: A = (N / A + A) / 2 
template <typename T, T N, T A, size_t I> struct Sqrt {
    static const T value = Sqrt<T, N, (N / A + A) / 2, I - 1>::value;
};
template <typename T, T N, T A> struct Sqrt<T, N, A, 0> {
    static const T value = A;
};

Thanks

  • Did you mean to have a [variadic template](http://stackoverflow.com/questions/17652412/what-are-the-rules-for-the-token-in-the-context-of-variadic-template/17652683#17652683) parameter list? – πάντα ῥεῖ Mar 27 '14 at 01:44
  • I'm just not sure why I'm getting the error "too many template arguments" when I have a template that accepts 4 arguments and I also pass 4 arguments. – user1843915 Mar 27 '14 at 01:51
  • Show the exact error and the usage of `Sqrt` or we won't believe you. – Captain Obvlious Mar 27 '14 at 01:55
  • The name of the `Sqrt` template class is unique though, and you have this previous declaration of `template struct Sqrt` which takes 2 arguments. You'll either need to use appropriate template parameter defaults, or the mentioned ellpsis (`...`) to specify a variadic template parameter list. – πάντα ῥεῖ Mar 27 '14 at 01:56
  • @CaptainObvlious No, not that kind oblivious that time ;) ... – πάντα ῥεῖ Mar 27 '14 at 01:57
  • That was the full error and I compiled it without calling it. If i remove the topmost template with 2 parameters and manually pass A and I then it works though, thanks – user1843915 Mar 27 '14 at 02:08

1 Answers1

1

The code can be much simpler than what you are thinking of.

#include <iostream>

template<int N, int M> struct Sqrt
{
   static const int value = (Sqrt<N, M-1>::value + N/Sqrt<N, M-1>::value)/2;
};

template<int N> struct Sqrt<N, 0>
{
   static const int value = N/2;
};


int main()
{
   int y = Sqrt<200, 10>::value;
   std::cout << "Sqrt(200): " << y << std::endl;

   y = Sqrt<200, 20>::value;
   std::cout << "Sqrt(200): " << y << std::endl;

   y = Sqrt<2000, 10>::value;
   std::cout << "Sqrt(2000): " << y << std::endl;

   y = Sqrt<2000, 20>::value;
   std::cout << "Sqrt(2000): " << y << std::endl;
}

The results, listed below, are approximate since we are working with only integer values.

Sqrt(200): 14
Sqrt(200): 14
Sqrt(2000): 44
Sqrt(2000): 44

However, when I tried to compute the square root of a number that is a perfect square, I got perfect answers.

   y = Sqrt<10000, 10>::value;
   std::cout << "Sqrt(10000): " << y << std::endl;

   y = Sqrt<10000, 20>::value;
   std::cout << "Sqrt(10000): " << y << std::endl;
Sqrt(10000): 100
Sqrt(10000): 100
R Sahu
  • 204,454
  • 14
  • 159
  • 270