首页 > 解决方案 > 什么是 C++ 中的编译时函数?

问题描述

我在这里(在 SO 上)搜索了这个问题,据我所知,所有问题都假设什么是编译时函数,但初学者几乎不可能知道这意味着什么,因为知道这一点的资源非常罕见。

我发现了一个简短的维基百科文章,它展示了如何通过在 C++ 中编写从未见过的枚举使用来编写难以理解的代码,以及一个关于它的未来的视频,但对此几乎没有解释。

在我看来,在 C++ 中编写编译时函数有两种方法

  1. constexpr
  2. template<>

我已经对它们进行了简短的介绍,但我不知道它们是如何出现在这里的。

谁能用一个足够好的例子来解释编译时函数,使它包含它最相关的特性?

标签: c++templatesconstexprcompile-time

解决方案


正如您所提到的,在 cpp 中,有两种方法可以在编译时评估代码 -constexpr函数和template元编程。

这些解决方案之间存在一些差异。该template选项较旧,因此受到更广泛的编译器的支持。Additionalytemplate保证在编译时被评估,而constexpr有点像 inline - 它只建议编译器可以在编译时进行工作。并且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;
}

推荐阅读