您可以使用模板预先计算 2 的幂表吗?

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

本文关键字:计算 可以使      更新时间:2023-10-16

当我问一个问题时,它说明了找到 2 次幂的最快方法是什么,我得到的答案是"预先计算它们并使用查找表"。

如何使用模板预先计算 2 的幂表?

链接到我之前的问题:找到 2 的幂的更好方法

这里有一个想法:

constexpr std::array<unsigned long long, 16> LUT = {
     1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768 };
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
}

实时代码在这里
我仍然宁愿1U << n而不是pow2<n>::value,除非有强有力的证据表明性能下降。