C++: calling non-member functions with the same syntax of member ones
Posted
by
peoro
on Stack Overflow
See other posts from Stack Overflow
or by peoro
Published on 2011-01-17T14:27:21Z
Indexed on
2011/01/17
14:53 UTC
Read the original article
Hit count: 249
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 inA
's virtual table.f
doesn't need to accessA
's non-public members.f
doesn't conflict with a function declared inA
(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 astd::string
(wherestrip
is a function defined by the user) would sound a lot better than callingstrip( 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.
© Stack Overflow or respective owner