c++ - 将参数传递给 constexpr 函数

标签 c++ constexpr

我是编程新手,我开始使用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. A constepxr 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() a Point argument, it returns a point with coordinates scaled according to the factors xscale and yscale. 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 是否被视为常量表达式? 如果是,为什么?

数据成员 xy 是否可以视为常量表达式?

我的书没有提供太多信息,所以我在这个概念上遇到了一些问题。

最佳答案

基本上,constexpr 函数可以根据上下文在编译时或运行时执行。只有当它的所有参数都是 constexpr 并且它的结果在需要 constexpr 的上下文中使用时才保证在编译时执行(例如,分配给 constexpr 值、模板参数,或者说,c 样式的数组大小)。否则,它将在运行时作为任何其他函数进行评估。所以 p3p4 行在运行时执行,而 p5 给出一个错误,因为 scale(p1) 是不是 constexpr,实际上 p6 也应该给你一个错误,除非你在 p2 的定义中添加一个 constexpr .查看示例 here .

关于c++ - 将参数传递给 constexpr 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32248698/

相关文章:

c++ - 什么是constexpr?

c++ - 使用方法失败更改 constexpr 对象成员

C++ 未知类型名称模板 - Eclipse

c++ - 关于常量表达式的困惑

c++ - 如何解析末尾带有可选分隔符的列表?

c++ - 没有下一行的标准控制台输出

c++ - 强制在编译时评估 constexpr

c++ - 你能使用 constexpr 变量的地址吗?

C++11:boost::make_tuple 与 std::make_tuple 有何不同?

库中的 C++ 常量;不起作用