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

后端 未结 17 1856
醉梦人生
醉梦人生 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:40

    Comparison to 0 doesn't work so well. Which comes back -- why !! vs. ternary?

    class foo { public: explicit operator bool () ; };
    
    foo f;
    
    auto a = f != 0; // invalid operands to binary expression ('foo' and 'int')
    auto b = f ? true : false; // ok
    auto c = !!f; // ok
    

提交回复
热议问题