Can you pre-compute a table of powers of 2 using templates

602 views Asked by At

When I asked a question, that states what is the fastest way to find the powers of 2, I get the answer "precompute them and use a lookup table".

How can I pre-compute a table of powers of 2 using templates?

Link to my previous question: Better way to find the powers of 2

2

There are 2 answers

0
sehe On BEST ANSWER

Here's an idea:

constexpr std::array<unsigned long long, 16> LUT = {
     1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 };
0
Mohit Jain On
template <int N>
struct pow2 
{
    enum { value = 2 * pow2<N - 1>::value };
};

template <>
struct pow2<0> 
{
    enum { value = 1 };
};

void foo()
{
    const int x = pow2<4>::value; // == 16
    const int y = pow2<0>::value; // == 1
    int arr[x] = {0}; // Because x is constant
}

Live code here
Still I would prefer 1U << n over pow2<n>::value unless there are strong evidences of performance degradation.