[这个问题与这个.]
如果我尝试将某些类型的值用作布尔表达式,则会收到警告.我有时会使用三元运算符 (?:
) 来转换为 bool,而不是取消警告.使用两个非运算符 (!!
) 似乎做同样的事情.
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?
那么,双重非技术真的能做同样的事情吗?它比三元技术更安全还是更不安全?这种技术对于非整数类型是否同样安全(例如,void *
或 double
用于 T
)?
So, does the double-not technique really do the same thing? Is it any more or less safe than the ternary technique? Is this technique equally safe with non-integral types (e.g., with void *
or double
for T
)?
我不是在问 !!t
是否是好的风格.我在问它在语义上是否与 t 不同?真:假
.
I'm not asking if !!t
is good style. I am asking if it is semantically different than t ? true : false
.
!运算符和三元运算符的第一个参数都隐式转换为 bool,所以 !!和?: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 的安全方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!