why std::string is not implicitly converted to bool

前端 未结 4 1335
暖寄归人
暖寄归人 2021-02-18 23:35

Is there a reason why in c++ std::string is not implicitly converted to bool? For example

std::string s = \"\"
if (s) { /* s in not empty */ }
         


        
4条回答
  •  眼角桃花
    2021-02-19 00:09

    The closest thing to what you (and I) want, that I've been able to find, is the following.

    You can define the ! operator on std::string's like so:

    bool operator!(const std::string& s)
    {
        return s.empty();
    }
    

    This allows you to do:

    std::string s;
    if (!s)             // if |s| is empty
    

    And using a simple negation, you can do:

    if (!!s)            // if |s| is not empty
    

    That's a little awkward, but the question is, how badly do you want to avoid extra characters? !strcmp(...) is awkward, too, but we still functioned and got used to it, and many of us preferred it because it was faster than typing strcmp(...) == 0.

    If anyone discovers a way to do if (s), in C++, please let us know.

提交回复
热议问题