When does a constexpr function get evaluated at compile time?(何时在编译时评估 constexpr 函数?)
问题描述
既然可以在运行时调用声明为 constexpr 的函数,那么编译器根据什么标准决定是在编译时还是在运行时计算它?
Since it is possible that a function declared as constexpr can be called during run-time, under which criteria does the compiler decide whether to compute it at compile-time or during runtime?
template<typename base_t, typename expo_t>
constexpr base_t POW(base_t base, expo_t expo)
{
return (expo != 0 )? base * POW(base, expo -1) : 1;
}
int main(int argc, char** argv)
{
int i = 0;
std::cin >> i;
std::cout << POW(i, 2) << std::endl;
return 0;
}
在这种情况下, i 在编译时是未知的,这可能是编译器将 POW() 视为在运行时调用的常规函数的原因.然而,这种动态虽然看起来很方便,但也有一些不切实际的含义.例如,是否存在我希望编译器在编译时计算 constexpr 函数的情况,编译器决定将其视为普通函数,而在编译时它也可以工作?是否有任何已知的常见陷阱?
In this case, i is unknown at compile-time, which is probably the reason why the compiler treats POW() as a regular function which is called at runtime. This dynamic however, as convenient as it may appear to be, has some impractical implications. For instance, could there be a case where I would like the compiler to compute a constexpr function during compile-time, where the compiler decides to treat it as a normal function instead, when it would have worked during compile-time as well? Are there any known common pitfalls?
推荐答案
constexpr
函数将在编译时被评估,当它的所有参数都是常量表达式并且结果是也用于常量表达式.常量表达式可以是文字(如 42
)、非类型模板参数(如 template
),一个 N
;enum
元素声明(如 enum Color { Red, Blue, Green };
中的 Blue
,另一个变量声明 constexpr,等等.
constexpr
functions will be evaluated at compile time when all its arguments are constant expressions and the result is used in a constant expression as well. A constant expression could be a literal (like 42
), a non-type template argument (like N
in template<class T, size_t N> class array;
), an enum
element declaration (like Blue
in enum Color { Red, Blue, Green };
, another variable declared constexpr, and so on.
当其所有参数都是常量表达式并且结果不用于常量表达式时,它们可能被评估,但这取决于实现.
They might be evaluated when all its arguments are constant expressions and the result is not used in a constant expression, but that is up to the implementation.
这篇关于何时在编译时评估 constexpr 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:何时在编译时评估 constexpr 函数?
基础教程推荐
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01