C++: calling non-member functions with the same syntax of member ones
- by peoro
One thing I'd like to do in C++ is to call non-member functions with the same syntax you call member functions:
class A { };
void f( A & this ) { /* ... */ }
// ...
A a;
a.f(); // this is the same as f(a);
Of course this could only work as long as
f is not virtual (since it cannot appear in A's virtual table.
f doesn't need to access A's non-public members.
f doesn't conflict with a function declared in A (A::f).
I'd like such a syntax because in my opinion it would be quite comfortable and would push good habits:
calling str.strip() on a std::string (where strip is a function defined by the user) would sound a lot better than calling strip( str );.
most of the times (always?) classes provide some member functions which don't require to be member (ie: are not virtual and don't use non-public members). This breaks encapsulation, but is the most practical thing to do (due to point 1).
My question here is: what do you think of such feature? Do you think it would be something nice, or something that would introduce more issues than the ones it aims to solve? Could it make sense to propose such a feature to the next standard (the one after C++0x)?
Of course this is just a brief description of this idea; it is not complete; we'd probably need to explicitly mark a function with a special keyword to let it work like this and many other stuff.