Log-base-2 function as compile-time constant



 DEVELOP > c-Plus-Plus > Log-base-2 function as compile-time constant

LINK TO THIS PAGE  


rating :  0   |  0


  Page 1 of 1

1

 
Topic: DEVELOP > c-Plus-Plus
User: "Frederick Gotham"
Date: 01 Jul 2006 09:57:03 AM
Object: Log-base-2 function as compile-time constant
I've mentioned his name a few times here lately, but over on comp.lang.c,
Hallvard B Furuseth has come up with a Log-base-2 function that serves as a
compile-time constant.
I'm not going to pretend to even begin to understand how it works, but if
anyone's interested, here's a link to the post:
http://groups.google.ie/group/comp.lang.c/msg/706324f25e4a60b0?hl=en&
Next time there's a rainy day, I might sit down with a pen and paper and
try to figure it out.
--
Frederick Gotham
.

User: "Luke Meyers"

Title: Re: Log-base-2 function as compile-time constant 02 Jul 2006 09:25:53 AM
Frederick Gotham wrote:

I've mentioned his name a few times here lately, but over on comp.lang.c,
Hallvard B Furuseth has come up with a Log-base-2 function that serves as a
compile-time constant.

I'm not going to pretend to even begin to understand how it works, but if
anyone's interested, here's a link to the post:

http://groups.google.ie/group/comp.lang.c/msg/706324f25e4a60b0?hl=en&

Next time there's a rainy day, I might sit down with a pen and paper and
try to figure it out.

My goodness, how convoluted. Luckily in C++ we have no need for such
macro-heavy measures when we want compile-time constants:
#include "boost/static_assert.hpp"
template <size_t N, size_t base=2>
struct log_
{
enum { value = 1 + log_<N/base, base>::value };
};
template <size_t base>
struct log_<1, base>
{
enum { value = 0 };
};
template <size_t base>
struct log_<0, base>
{
enum { value = 0 };
};
int main()
{
BOOST_STATIC_ASSERT(log_<0>::value == 0);
BOOST_STATIC_ASSERT(log_<1>::value == 0);
BOOST_STATIC_ASSERT(log_<2>::value == 1);
BOOST_STATIC_ASSERT(log_<3>::value == 1);
BOOST_STATIC_ASSERT(log_<4>::value == 2);
BOOST_STATIC_ASSERT(log_<5>::value == 2);
BOOST_STATIC_ASSERT(log_<8>::value == 3);
BOOST_STATIC_ASSERT(log_<16>::value == 4);
BOOST_STATIC_ASSERT(log_<246>::value == 7);
return 0;
}
Experiment to your heart's content with other bases, negative numbers,
limits, etc.
Cheers,
Luke
.


  Page 1 of 1

1

 


Related Articles
 

NEWER

pg.1232     pg.940     pg.716     pg.544     pg.412     pg.311     pg.234     pg.175     pg.130     pg.96     pg.70     pg.50     pg.35     pg.24     pg.16     pg.10     pg.6     pg.3     pg.1

OLDER