如果是非布尔条件,则为Constexpr [英] Constexpr if with a non-bool condition

查看:87
本文介绍了如果是非布尔条件,则为Constexpr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎找到了Clang和GCC不一致的东西.这是代码:

I seem to have found something that Clang and GCC disagree on. Here's the code:

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

这可以在GCC 7.4.0上成功编译,但是在Clang 7.0.0上却失败,并显示以下错误消息:

This successfully compiles with GCC 7.4.0, but it fails with Clang 7.0.0 with this error message:

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错误一样,但我不确定.如果这是任何一个编译器的错误,是否已经报告过?

cppreference doesn't seem to mention "narrowing", so this seems like a Clang bug, but I'm not entirely certain. If this is a bug with either compiler, has it already been reported?

推荐答案

Clang正在根据以下段落进行诊断

Clang is diagnosing under these paragraphs

[stmt.if] (强调我的意思)

[stmt.if] (emphasis mine)

2 如果if语句的形式为if constexpr,的值 条件应为的上下文转换常量表达式 输入bool ;这种形式称为constexpr if语句.

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 类型T的转换常量表达式是一个表达, 隐式转换为T类型,其中转换后的表达式为 常量表达式,并且隐式转换序列仅包含

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

  • 积分转化,而不是缩小转化率,

现在,当涉及整数转换时,将转换为 bool

Now, when it comes to integral conversions, a conversion to bool is listed as an integral conversion. And it is narrowing, in the strictest sense of the word, since a bool cannot represent all the values of an int. So the diagnostic is not without grounds.

但是,我认为考虑转换为bool通常是为了检查真实性"这一事实也是很合理的,因此,其狭义性质并不重要.它看起来像是标准 1 中的一个小错误,GCC采用了常识性路线,而Clang在最严格的意义上坚持了法律的枯燥乏味.

But I think it's also quite reasonable to consider the fact a conversion to bool is usually intended to check for "truthiness", and so the narrowing nature of it shouldn't matter. It looks like a minor bug in the standard1, with GCC taking the common-sense route, and Clang adhering to the dry letter of the law in the strictest sense.

1 -和存在一项更改提案的提案.

1 - And a proposal exists to change it.

这篇关于如果是非布尔条件,则为Constexpr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆