Hello, I would like to know if the extension methods proposal (such as presented in this paper :
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0079r0.pdf) is considered for C++20.
This proposal allows to define free functions available with the member function syntax, for existing
classes :
struct int_array {
int* data;
int size;
};
// 'this' makes back an extension method
// Usage : myArray.back()
int& back(int_array
array* this) {
return *(array.data + size - 1)
;
}
I think there is great benefits to implement functions as not member ones :
We get a better encapsulation because less functions can act on the private object's state
We can add behavior to existing classes and (optionnally constrained) template classes without
modifying them
But when it comes to using the function, I prefer the member function syntax :
It is easier to read (well, for me)
It permit proper chaining of function calls (a.f1().f2() rather than f2(f1(a)))
Is what is currently widely adopted to act on an object, at the point where the same functions
are copyied to be added to similar classes
It is more friendly to use with a development environment proposing which member functions are
available for the current object
Moreover, with concepts surely incoming with C++20,
(
https://www.reddit.com/r/cpp/comments/854mu9/2018_jacksonville_iso_c_committee_reddit_trip/)
we could define extension methods for concepts.
A well-known exemple is LINQ in C# : it is available for every class which implement IEnumerable
(an equivalent of C++ iterable containers, with begin() and end()).
Here is a little exemple in C#, where 'Where' and 'Take' functions are extension methods.
var meal = EnumerateFridge()
.Where(food => food.HasChocolate())
.Take(7);