Template Metaprogramming

E

E. Rosten

OK, how do I calculate the root of a number w/TMP?

Here's the simplest way possible:

//START
template<int i, int dec=-1, int less=-1> struct Sqrt
{
static const int val=Sqrt<i, dec-1, (dec*dec<=i) >::val;
};

template<int i, int dec> struct Sqrt<i, dec, 1>
{
static const int val=dec+1;
};

template<int i> struct Sqrt<i, -1, -1>
{
static const int val=Sqrt<i, i, 0>::val;
};
//END

example:

cout << sqrt<386>::val << endl;


Of course, for large values, it might take a while, and you'll need to set
ypur template recursion depth quite high. You might wish to consider using
a more advanced technique such as binary search or Newton's method.

-Ed





--
(You can't go wrong with psycho-rats.) (er258)(@)(eng.cam)(.ac.uk)

/d{def}def/f{/Times findfont s scalefont setfont}d/s{10}d/r{roll}d f 5/m
{moveto}d -1 r 230 350 m 0 1 179{1 index show 88 rotate 4 mul 0 rmoveto}
for /s 15 d f pop 240 420 m 0 1 3 { 4 2 1 r sub -1 r show } for showpage


[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top