by Strilanc · 1y ago · 0 comments
Ah yes, C++, the discerning language.
Iterating over optional does seem syntactically convenient. My main question would be if it guarantees no overhead. For example, is there an additional conditional branch due to the iterator hiding the statically know fact that there's at most one iteration? I don't use C++ for its beauty, I use it for speed.
The main difference there seems to be that GCC treats the if() as unlikely to be taken while the for() as likely.
C++, the language that refused to add `contains()` to maps until, you know, C++20!
Absolutely incredible, definitely worth the wait
Rust will also let you: "FOO".contains(char::is_uppercase)
That's showing off three clever tricks Rust has that C++ does not, but one day it will just be compile time evaluated as true and that's one place C++ is richer today. Many other things in Rust can be but Rust's traits aren't today allowed to be compile time evaluated, so the fact that we could determine at compile time whether there's an uppercase letter in FOO isn't enough yet. One day.
namespace std {
class string {
bool contains(const string& other) & {
//Check if 'this' is in 'other'
}
bool contains(const string& other) && {
//check if 'other' is in 'this'
}
};
}
using namespace std::string_literals;
int main() {
string foo("foo bar foo");
foo.contains("bar"); //returns true
"bar"s.contains("foo bar foo"); //returns true
}
But I hope not because this 'flipping the script' behavior just makes the code flow more difficult to reasonate about.