我在这里(在 SO 上)搜索了这个问题,据我所知,所有问题都假设什么是编译时函数,但初学者几乎不可能知道这意味着什么,因为知道那是非常罕见。
我找到了短 wikipedia article它展示了如何通过在 C++ 中使用以前从未见过的枚举来编写难以理解的代码,以及 video这是关于它的 future ,但对此解释得很少。
在我看来,在C++中编写编译时函数有两种方式
-
constexpr
-
template<>
我已经对它们进行了简短的介绍,但我不知道它们是如何出现在这里的。
谁能用一个足够好的例子来解释编译时函数,使其包含它的大部分相关特性?
最佳答案
如您所述,在 cpp 中,有两种在编译时评估代码的方法 - constexpr
函数和 template
元编程。
这些解决方案之间存在一些差异。 template
选项较旧,因此得到更广泛的编译器支持。另外 template
保证在编译时进行评估,而 constexpr
有点像内联 - 它只建议编译器可以在编译时进行工作。对于 templates
,参数通常通过模板参数列表传递,而 constexpr
函数将参数作为常规函数(它们实际上是)。 constexpr
函数更好,因为它们可以在运行时作为常规函数调用。
现在是相似之处 - 它们的参数必须可以在编译时进行评估。因此它们必须是文字或其他编译时函数的结果。
说了这么多让我们来看看编译时的 max
函数:
template<int a, int b>
struct max_template {
static constexpr int value = a > b ? a : b;
};
constexpr int max_fun(int a, int b) {
return a > b ? a : b;
}
int main() {
int x = 2;
int y = 3;
int foo = max_fun(3, 2); // can be evaluated at compile time
int bar = max_template<3, 2>::value; // is surely evaluated at compile time
// won't compile without compile-time arguments
// int bar2 = max_template<x, y>::value; // is surely evaluated at compile time
int foo = max_fun(x, y); // will be evaluated at runtime
return 0;
}
关于c++ - C++ 中的编译时函数是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61888854/