简体   繁体   English

从LANGUAGE DESIGN级别看,为什么“如果constexpr”在编译时无法推断出条件时会“衰减”

[英]From LANGUAGE DESIGN level, why doesn't “if constexpr” decay to “trival if” when condition cannot be deduced at compile-time

As we know, when constexpr function 's return value cannot be known at compile-time , it will be delayed to be computed at run-time (IOW, decay to non-constexpr function ). 我们知道,当在compile-time无法知道constexpr function的返回值compile-time ,它将被延迟在run-time计算(IOW,衰减到non-constexpr function )。 This allows us to adhere constexpr to a function freely and need not worry about any overhead. 这使我们能够自由地将constexpr到函数中,而不必担心任何开销。

I think it can also apply to if statement . 我认为它也适用于if statement Since c++17, we have if constexpr , so we can use compile-time if statement easily(without true_type / false_type . Unlike constexpr function , however, it will fail if its condition cannot be known at compile-time: 从c ++ 17开始,我们有if constexpr ,所以我们可以很容易地使用compile-time if statement (没有true_type / false_type 。但是,与constexpr function不同,如果在编译时无法知道它的条件,它将会失败:

constexpr int factorial(int n)
{
    if constexpr(n == 0) return 1;
    else return n * factorial(n-1);
}

So, the codes above cannot pass compilation because n is not a constant expression. 因此,上面的代码无法通过编译,因为n不是常量表达式。 But certainly, the function can be calculated at compile-time when input is known at compile-time . 但当然, compile-time时输入已知时可以在compile-time时计算函数

For the same reason that swallowing errors/exceptions and just plowing through is bad. 出于同样的原因,吞咽错误/异常和只是翻耕是不好的。 It can potentially put your program in some sort of unspecified state. 它可能会使您的程序处于某种未指定的状态。 Making it almost impossible to reason about. 几乎无法推理。

If a constraint in a program isn't met, the person who wrote it and relied on it needs to be notified promptly. 如果不满足程序中的约束,则需要立即通知编写并依赖它的人。 Making such a thing a hard error for a language construct makes sense. 对于语言结构来说,这样的事情是一个很难的错误是有道理的。 Especially if the language construct drive the actual generation of code. 特别是如果语言结构驱动实际的代码生成。

In this case the constraint is b being a valid constant expression. 在这种情况下,约束是b是有效的常量表达式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM