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.l...e4a60b0?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