C++ – Calling Non-Member Functions with Member Syntax

clanguage-designlanguage-features

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:

  1. 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 );.

  2. 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.

Best Answer

re your #2: Actually, making functions non-members often increases encapsulation, as Scott Meyers observed more than a decade ago.

Anyway, what you describe sounds much like C#'s extension methods to me. They are good to soothe the minds of those that are frightened when they see totally free functions. :) Once you've braved the STL (which, BTW, is not the standard library, but only that part of it which comes from the original STL) where almost all functions are so free that they aren't even real functions, but function templates, you will no longer need those.

In short: Don't try to bend a language to adapt to your mindset. Instead enhance your mindset to embrace the language's philosophy. You will emerge a bit taller from doing so.