c++ - C++ 中的编译时函数是什么?

标签 c++ templates constexpr compile-time

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

我找到了短 wikipedia article它展示了如何通过在 C++ 中使用以前从未见过的枚举来编写难以理解的代码,以及 video这是关于它的 future ,但对此解释得很少。

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

  1. constexpr
  2. 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/

相关文章:

C++ operator setter ruby​​ 风格

c++ - Microsoft Visual C++ 连接到 Unix 环境

c++ - 更改添加隐藏 this 指针的方法是否会破坏二进制兼容性?

c++ - 如何为模板类的所有实例专门化或重载全局模板函数?

c++ - 使用 libpcap,有没有办法从离线 pcap 文件中确定捕获数据包的文件偏移量?

c++ - 是否可以在模板化类之外获取分配的模板类型?

c++通过构造函数选择推断bool类模板参数

c++ - 我如何确认我的constexpr表达式实际上已经在编译时执行了

c++ - 如何将 const 数组存储在可执行文件中?

C++ private static constexpr 成员变量