gpt4 book ai didi

c++ - Consexpr if 具有非 bool 条件

转载 作者:IT老高 更新时间:2023-10-28 14:02:07 25 4
gpt4 key购买 nike

我似乎发现了 Clang 和 GCC 不同意的地方。代码如下:

int main() {
if constexpr (2) {}
}

使用 GCC 7.4.0 编译成功,但使用 Clang 7.0.0 编译失败,并显示以下错误消息:

test.cpp:3:17: error: constexpr if condition evaluates to 2, which cannot be narrowed to type 'bool'
[-Wc++11-narrowing]
if constexpr (2) {}
^
1 error generated.

cppreference似乎没有提到“缩小”,所以这似乎是一个 Clang 错误,但我并不完全确定。如果这是任一编译器的错误,是否已报告?

最佳答案

Clang 正在根据这些段落进行诊断

[stmt.if] (emphasis mine)

2 If the if statement is of the form if constexpr, the value of the condition shall be a contextually converted constant expression of type bool; this form is called a constexpr if statement.

[expr.const]

4 A converted constant expression of type T is an expression, implicitly converted to type T, where the converted expression is a constant expression and the implicit conversion sequence contains only

  • integral conversions other than narrowing conversions,

现在,当涉及到整数转换时,to bool is listed as an integral conversion .从最严格的意义上讲,它正在缩小,因为 bool 不能代表 int 的所有值。所以诊断并非没有根据。

但我认为考虑到 bool 的转换通常是为了检查“真实性”这一事实也是相当合理的,因此它的缩小性质应该无关紧要。它看起来像是标准1 中的一个小错误,GCC 走的是常识路线,而 Clang 遵守最严格意义上的法律条文。


<子>1 - 和 a proposal exists to change it .

关于c++ - Consexpr if 具有非 bool 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54899466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com