3 ms·
I must not have explained it well enough. Take std::string. It is missing majorly useful functions that exist in other languages, such as trim, transform, spli
by byuu 12y ago
I must not have explained it well enough.
Take std::string. It is missing majorly useful functions that exist in other languages, such as trim, transform, split/explode/tokenize, replace-by-string (std::string is replace-by-length, which is more like memcpy), etc.
You can add those functions. But you can't add them into std::string. So you get: void trim(string& s, const string& trim);
And now your code is a mix of two styles:
s.append(" Hello, World ");
trim(s, " ");
s.compare(...);
As I've explained, subclassing is dangerous. Two people each add their own functions to their own derived types, and now those types aren't directly compatible without slicing back to std::string.
So the problem, as a class author, is that you want to add all of the functions a user might want, so that they can consistently use the same syntax. So when you write your string class, users can then use it like so:
s.append(" Hello, World ");
s.trim(" ");
s.compare(...);
//or even possibly ...
s.append(" Hello, World ").trim(" ").compare(...);
(You may say the syntax difference doesn't matter, but I disagree strongly: it's burdensome to remember which functions are string::foo(), and which functions are foo(string&); and if I wanted to use foo(string&) exclusively, then I'd go back to writing in C.)
This causes substantial bloat by packing string with a ridiculous number of functions.
Some of those functions are going to be very niche. For instance, I have find/replace/split functions that ignore values inside of quotes, which I use extensively in a cross assembler I wrote. But they're not very useful for my other programs. It would be nice if I could #include <string/extension/quoted-strings.hpp> for the cross assembler, which would contain UFCS functions, and leave this out of my other projects. Smaller compilation times, and easier to create experimental/fluid extensions before committing them to the official class API.
And if a user of my string library decided that they needed additional functions, they too could add them.
I would go so far as to say that UFCS will result in more developers using the C++ standard library containers and types, rather than rolling their own. Which would be a huge win for the language.