将值转换为 bool 的魔法 [英] Magic of casting value to bool

查看:34
本文介绍了将值转换为 bool 的魔法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我意识到将值转换为 bool 是一种魔法:

Today I realized that casting a value to a bool is a kind of magic:

int value = 0x100;
unsigned char uc = static_cast<unsigned char>(value);
bool b = static_cast<bool>(value);

sizeof(uc)sizeof(b) 都返回 1.我知道 uc 将包含 0x00,因为只有 LSB 被复制.但是 b 将是 true,所以我的假设是,当转换为 bool 时,该值会被评估而不是被复制.

Both sizeof(uc) and sizeof(b) return 1. I know that uc will contain 0x00, because only the LSB is copied. But b will be true, so my assumption is that, when casting to bool, the value gets evaluated instead of copied.

这个假设正确吗?这是标准的 C++ 行为吗?

Is this assumption correct? And is this a standard C++ behavior?

推荐答案

它没有什么神奇之处.从 intunsigned char 的转换定义为 value % 256(对于 8 位 chars),所以这就是你得到的.可以实现为复制LSB,但你还是应该从语义的角度考虑,而不是实现.

There's nothing magical about it. The conversion from int to unsigned char is defined as value % 256 (for 8-bit chars), so that is what you get. It can be implemented as copying the LSB, but you should still think about it in the semantic sense, not the implementation.

同样,intbool 的转换被定义为 value != 0,同样,这就是你得到的.

On the same vein, conversion of int to bool is defined as value != 0, so again, that is what you get.

[conv.integral][conv.bool] 中的 C++11 标准涵盖了积分(和布尔)转换.对于 C 风格的转换,请参见 [expr.cast][expr.static.cast].

Integral (and boolean) conversions are covered by the C++11 standard in [conv.integral] and [conv.bool]. For the C-style cast, see [expr.cast] and [expr.static.cast].

这篇关于将值转换为 bool 的魔法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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