c++ - 什么是 C++ 中的编译时函数?
问题描述
我在这里(在 SO 上)搜索了这个问题,据我所知,所有问题都假设什么是编译时函数,但初学者几乎不可能知道这意味着什么,因为知道这一点的资源非常罕见。
我发现了一个简短的维基百科文章,它展示了如何通过在 C++ 中编写从未见过的枚举使用来编写难以理解的代码,以及一个关于它的未来的视频,但对此几乎没有解释。
在我看来,在 C++ 中编写编译时函数有两种方法
constexpr
template<>
我已经对它们进行了简短的介绍,但我不知道它们是如何出现在这里的。
谁能用一个足够好的例子来解释编译时函数,使它包含它最相关的特性?
解决方案
正如您所提到的,在 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;
}
推荐阅读
- jquery - Jquery最接近没有用replace定义
- ios - 是否可以将手势识别器附加到按钮,以便用户在按下按钮之后/期间向上滑动?
- php - Laravel 使用 vendor 目录 php 类
- php - PHPMailer没有发送一些电子邮件
- javascript - 检查未定义“值”的方法
- c# - Entity Framework Core 中的条件导航属性
- matrix - 在 Julia 的矩阵中找到最大值的位置
- node.js - 如何删除 apiconnect 路径上的安全要求?
- sql-server - 加入 iTVF 可以像加入临时表一样快吗?
- opc-ua - 连接到远程 OPCUA 服务器的问题