Is !! a safe way to convert to bool in C++?

后端 未结 17 1905
醉梦人生
醉梦人生 2020-11-29 22:25

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

If I try to use values of certain types as boolean expressions, I get a warning. Rather than su

17条回答
  •  悲哀的现实
    2020-11-29 22:50

    I recommend never suppressing that warning, and never using a c cast (bool) to suppress it. The conversions may not always be called as you assume.

    There is a difference between an expression that evaluates to true and a boolean of that value.

    Both !! and ternary take getting used to, but will do the job similarly, if you do not want to define internal types with overloaded casts to bool.

    Dima's approach is fine too, since it assigns the value of an expression to a bool.

提交回复
热议问题