我是编程新手,我开始使用Programming principle and practice using C++一书了解它。今天我来这里是因为我在理解 constexpr
函数方面遇到了一些问题。在第 8 章中,作者用几行介绍了它们,并用这些词做了一个简短的例子:
A function represents a calculation, and sometimes we want to do a calculation at compile time. The reason to want a calculation evaluated by the compiler is usually to avoid having the same calculation done millions of times at run time.
We convey our intend to have a function evaluated at compile time by declaring the function as a
constexpr
function. Aconstepxr
function can be evaluated at compile time just if it is given constant expressions as arguments.constexpr double xscale = 10; // scaling factors constexpr double yscale = 0.8; constexpr Point scale(Point p) { return { xscale*p.x, yscale*p.y }; };
Assume that point is a simple struct with members x and y representing 2D coordinates. Now, when we give
scale()
aPoint
argument, it returns a point with coordinates scaled according to the factorsxscale
andyscale
. For example:void user(Point p1) { Point p2{10,10}; Point p3 = scale(p1); Point p4 = scale(p2) // p4 == {100,8} constexpr Point p5 = scale(p1); // error : scale(p1) is not a constant expression constexpr Point p6 = scale(p2); // p6 == {100,8};
我的问题是:为什么我们可以使用 p2
作为 scale()
的参数? p2
是否被视为常量表达式? 如果是,为什么?
数据成员 x
和 y
是否可以视为常量表达式?
我的书没有提供太多信息,所以我在这个概念上遇到了一些问题。
最佳答案
基本上,constexpr
函数可以根据上下文在编译时或运行时执行。只有当它的所有参数都是 constexpr
并且它的结果在需要 constexpr
的上下文中使用时才保证在编译时执行(例如,分配给 constexpr
值、模板参数,或者说,c 样式的数组大小)。否则,它将在运行时作为任何其他函数进行评估。所以 p3
和 p4
行在运行时执行,而 p5
给出一个错误,因为 scale(p1)
是不是 constexpr
,实际上 p6
也应该给你一个错误,除非你在 p2
的定义中添加一个 constexpr
.查看示例 here .
关于c++ - 将参数传递给 constexpr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32248698/