您可以使用模板预先计算 2 的幂表吗?
Can you pre-compute a table of powers of 2 using templates
当我问一个问题时,它说明了找到 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
,除非有强有力的证据表明性能下降。
相关文章:
- 是否可以使C++类成为Objc类的委托
- 是否可以使一个类成为两个不同层次结构的子类?
- 是否有编译器标志可以使较新的 gcc 版本像旧版本一样构建
- C 可以使destuructor不称为班级成员和基类攻击方的灾难
- 浮点计算可以用于任何可靠的函数,特别是容器和算法吗?
- 可以使未命名的结构静态
- 是否可以使整数仅收到一个单个数字而不是两个接收输入
- C++:有哪些常规方法可以使代码更有效地用于大数字
- 是否可以使 std 容器使用默认运算符为新?
- LD_BIND_NOW可以使可执行文件运行得更慢?
- 是否可以使头文件使文本居中?- 在控制台中
- 为什么CPU上的螺纹浮点计算会使它们的花费明显更长
- 有什么方法可以使核心忙碌等待
- 有没有一种技术可以使虚函数在所有派生类中强制重写?
- 有没有一种方法可以使全局函数/静态成员函数一次可呼出
- 是否有一种方法可以使此C 14递归模板在C 17中短
- 编写一个可以使二维数组平坦的函数
- 有哪些优化技巧可以使我的代码运行得更快
- 有没有更好的方法可以使此代码线程安全?线程局部静态似乎是一个生硬的工具
- 有哪些技巧可以使包含大量计算的函数简洁