constexpr函数及其参数

constexpr函数及其参数

本文介绍了constexpr函数及其参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

constexpr int hello(int j) {
    return j * 12;
}

constexpr int bye(int j = 6) {
    return j * 12;
}

int main() {
    int i = 6;
    constexpr int a1 = hello(i); //error
    constexpr int a2 = hello(6); //ok
    constexpr int a3 = hello(int(6)); //ok
    constexpr int a4 = bye(); //ok
    constexpr int a5 = bye(i); //error
    constexpr int a6 = bye(6); //ok
    return 0;
}

hellow(i) hello(6)?我认为一个是 int j = i; 并且j不是constexpr,而另一个是 int j = 6 并且j仍然不是constexpr,两个j都是 int 类型。

int *文字!= constexpr ,因此返回类型不是constexpr。

What's difference between hellow(i) and hello(6)? I think one is int j = i; and j is not a constexpr, while the other is int j = 6 and j is still not a constexpr, both j are int type.
int * literal != constexpr, so the return type is not a constexpr.

我从书中的示例中得到了上述结论:

int staff_size = 27; // staff_size不是const表达式

I got the above conclusion from an example in the book:
int staff_size = 27; //staff_size is not a const expression

此外,我注意到 hello(int(6))也可以正常工作,这里的内容是什么?

Moreover, I notice that hello(int(6)) works fine too, what's the "thing" here?

另外, bye()起作用而 hello(i)不会,两个参数都在函数内部初始化,只有一个具有默认值,这有什么意义?

Additionally, bye() works while hello(i) does not, both parameter are initialized inside the function, only one with default value, what's the point here?

很困惑,希望有人可以解释一下:D

Very confused, hope someone could explain :D

PS:不知道要找出更好的标题,对此感到抱歉

PS: have no idea to figure out a better title, sorry for that

推荐答案

这里要注意的是编译器验证代码,而不是读取代码。

The thing to note here is that the compiler "validates" the code, it doesn't "read" it.

编译器期望constexpr的所有部分在编译时成为已知的有效常数。因此,尽管您和我从阅读代码中知道 i 的值永远不会改变,但编译器不会知道它,除非您声明 i 为常数。就其而言,您可能已在其他地方执行了其他代码来更改 i 的值。

The compiler expects all parts of a constexpr to be a known valid constant at compile time. So although you and I know, from reading the code, that the value of i never changes, the compiler doesn't "know" it unless you declare i to be a constant. As far as it is concerned you could have executed other code somewhere to change the value of i.

如果在没有 i 的情况下调用函数,编译器无疑会知道 j 是值为 6 的常量整数(注意: int(6)与只需 6 )。

In all the cases where the function is called without the i, the compiler knows for a fact, without a doubt, that the value of j is a constant integer with a value of 6, (note: int(6) is the same as just 6).

这篇关于constexpr函数及其参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 04:33