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 */ }
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.