是!一种安全的方式来转换在C ++中为bool? [英] Is !! a safe way to convert to bool in C++?

查看:131
本文介绍了是!一种安全的方式来转换在C ++中为bool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[这个问题是有关,但不一样的<一个href=\"http://stackoverflow.com/questions/206564/what-is-the-performance-implication-of-converting-to-bool-in-c\">this 之一。]

[This question is related to but not the same as this one.]

如果我尝试使用某些类型的值作为布尔前pressions,我得到一个警告。而不是燮preSS的警告,我有时用三元运算符()转换为布尔。使用两个没有运营商( !! ),似乎做同样的事情。

If I try to use values of certain types as boolean expressions, I get a warning. Rather than suppress the warning, I sometimes use the ternary operator (?:) to convert to a bool. Using two not operators (!!) seems to do the same thing.

这就是我的意思是:

typedef long T;       // similar warning with void * or double
T t = 0;
bool b = t;           // performance warning: forcing 'long' value to 'bool'
b = t ? true : false; // ok
b = !!t;              // any different?

所以,做双不是技术真正做同样的事情?这是任何比三元技术或多或少的安全吗?这是技术与非整数类型(例如:同样安全,使用无效* 双击 T )?

我不问是否!牛逼是好作风。我问,如果它比 T语义上有什么不同?真:假

I'm not asking if !!t is good style. I am asking if it is semantically different than t ? true : false.

推荐答案

的参数!运算符和三元运算符的第一个参数都是隐式转换为布尔,所以!!和:是的演员IMO傻多余的装饰。我投

The argument of the ! operator and the first argument of the ternary operator are both implicitly converted to bool, so !! and ?: are IMO silly redundant decorations of the cast. I vote for

b = (t != 0);

没有隐式转换。

这篇关于是!一种安全的方式来转换在C ++中为bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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