何时在编译时评估 constexpr 函数?

When does a constexpr function get evaluated at compile time?(何时在编译时评估 constexpr 函数?)
本文介绍了何时在编译时评估 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 函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

What do compilers do with compile-time branching?(编译器如何处理编译时分支?)
Can I use if (pointer) instead of if (pointer != NULL)?(我可以使用 if (pointer) 而不是 if (pointer != NULL) 吗?)
Checking for NULL pointer in C/C++(在 C/C++ 中检查空指针)
Math-like chaining of the comparison operator - as in, quot;if ( (5lt;jlt;=1) )quot;(比较运算符的数学式链接-如“if((5<j<=1)))
Difference between quot;if constexpr()quot; Vs quot;if()quot;(“if constexpr()之间的区别与“if())
C++, variable declaration in #39;if#39; expression(C++,if 表达式中的变量声明)