我如何在C 中计算在编译时进行计算
How can I calculate at compiletime in c++
如何计算一些数学表达式,即n的阶乘;在C ?
这是Wiki文章,内容涉及C 中的模板元编程。
这是另一本有关编译时函数执行的Wiki文章。
这是关于阶乘的一个问题。
让我们以编译时间进行计算阶乘的wiki xample。
template <int N>
struct Factorial {
enum { value = N * Factorial<N - 1>::value };
};
template <>
struct Factorial<0> {
enum { value = 1 };
};
// Factorial<4>::value == 24
// Factorial<0>::value == 1
const int x = Factorial<4>::value; // == 24
const int y = Factorial<0>::value; // == 1
由于所需的所有参数都是在编译时间中知道的(例如,在Factorial<4>
中明确提到了它们),因此编译器能够生成所有所需的代码。之后,Factorial<4>
结构的value
将为24,以后可以使用,就像您自己对其进行了硬编码一样。
欢迎来到所谓的模板元编程。
此页面描述了它是什么。它有一个特定的示例来计算编译时整数的阶乘。
相关文章:
- 断言中的Fold表达式在某些计算机上编译,但在其他计算机上不编译
- C++ 在编译时具有函数计算全局变量
- 如何在常量计算表达式中获取编译时错误?
- 如何判断是否在编译时计算了"constexpr"(无需手动检查)
- 在编译时何时计算范围::视图?
- C++编译器能在编译时计算出文字的除法结果吗
- 在编译时计算"if"子句
- 根据计算机上安装的库依赖项编译不同的代码
- 强制在编译时计算类的类的常量成员
- 在 64 位 Linux armv8 计算机上编译 32 位二进制文件时遇到问题
- 在编译时计算基类的偏移量
- C++ constexpr:在编译时计算标准数组
- 如何判断表达式是在编译时还是运行时计算的?
- 计算对数组编译时中对元素的差异
- C++ 计算编译时常量,同时防止整数常量溢出
- 在C++中,是否有内置的方法来计算编译时的功率
- 如何使用工会成员的大小计算编译时值
- 如何驱动 C#、C++ 或 Java 编译器计算 1+2+3+.编译时为 +1000
- 计算编译时数组时出现编译器相关错误
- 在C++11中计算编译时的斐波那契数(递归方法)(constexpr)