我如何在C 中计算在编译时进行计算

How can I calculate at compiletime in c++

本文关键字:计算 编译      更新时间:2023-10-16

如何计算一些数学表达式,即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,以后可以使用,就像您自己对其进行了硬编码一样。

欢迎来到所谓的模板元编程。

此页面描述了它是什么。它有一个特定的示例来计算编译时整数的阶乘。