4 ms·
I don't know what it's chances of ratification are -- it does seem like an aggressive change -- but I disagree that it doesn't add anything. This would actuall
by bodyfour 12y ago
I don't know what it's chances of ratification are -- it does seem like an aggressive change -- but I disagree that it doesn't add anything. This would actually fix one of the biggest problems I have with large C++ development: non-open classes.
Think of a widely used class -- for example lets use std::string. Maybe for your program there are some missing methods that would really handy to add, like maybe .urlencode(). Today in C++ you can't though: if the method isn't mentioned in the original definition of std::string in its header file it's permanently missing.
This leads to pressure to make a custom version of the class, either inheriting or encapsulating the original. This seems to work OK but then can lead to problems if you later want to interface with someone else's library written in C++. For instance you might have "class mystring : public std::string" and they have "class theirstring : ..." now you have to explicitly convert between them even if data-wise they're 100% compatible.
This proposal neatly solves this problem -- you could just implement string extensions as a function and still be able to call them like a regular method. The ability to add methods to other people's types promotes type reuse.
- jpatte 12y agoThe same result could be achieved by introducing a smaller change to the language that doesn't completely redefine the way existing functions are evaluated. By using some specific signature (like adding a keyword to the first argument of a function), you could indicate that this function may be used as a member method of the first argument. For example, C# uses the keyword 'this' for its extension methods: public static class Helpers { public static string UrlEncode(this string url) { //... } } // then later: string someText = "..."; string a = Helpers.UrlEncode(someText); // valid string b = someText.UrlEncode(); // valid too But of course that would mean having to update all the function declarations of the standard library to add the new keyword when needed...
- bodyfour 12y agoYes, I agree that there are simpler changes that would fix the problem, and personally I'd root for them. Stroustrup's proposal is still interesting in that it would solve it and unify operator/method dispatch at the same time. It has a certain elegance.