Extension methods in C++ -- Marius Bancila

Save to:
Instapaper Pocket Readability

Recently on Codexpert, an enthusiastic and very readable reaction to two fresh standards proposals that will be considered two weeks from now at the ISO C++ meeting in Urbana-Champaign, Illinois, USA:

Extension methods in C++

by Marius Bancila

From the article:

... if x.f(y) and f(x,y) were equivalent it would be very easy to write the above code like this:

auto v = std::vector<int> {1,2,3,4,5,6,7,8,9};

auto s = v.where([](int e){return e % 2 == 0; })
          .select([](int e){return e*e; })

Isn’t that beautiful? I think it is.


The N4174 paper is rather an exploration of possibilities for uniform calling syntax than a very formal proposal. There are various aspects that have to be carefully considered especially when considering how to treat f(x, y). The N4165 paper makes a good case of the uniform calling syntax, explains the benefits better and argues against treating f(x) equivalent to x.f(). You should go ahead and read the two papers for detailed information. However, I sincerely hope that one day this will be accepted and become a core feature of the C++ language.

Add a Comment

Comments are closed.

Comments (2)

0 0

Joaquin Luis Monleon Irisarri said on Aug 10, 2017 03:02 AM:

It's Beutiful, Isn't C/C++ the best language? smile

I'm also cryng for that happen too.

I must quietly read your post and the link I send, now don't have time, men at work.

There is philsquared implementation: https://gist.github.com/philsquared/5368140

Maybe help on your pourpouses.

0 0

Joaquin Luis Monleon Irisarri said on Aug 11, 2017 04:54 AM:

My solution I gonna use to add “C++ Extension Methods” to JNI jobjects to make NDK code more readable (Uniform Function Call Syntax).

* Subclass the class U want to add extension methods.
* For invoking the “Extension Methods” make a pointer of type ExtensionsClass to point to OriginalClass - (Although the pointed object is’nt an ExtensionsClass).

The overload is minimal & we can access public methods of the Original class.

#include <iostream>

#include <iostream>

class Person {
privateage = 20;
int age() { return privateage; }
int privateage;
short anotherField;

class PersonExtensions : private Person {
inline int size() { return 5 + age(); }

int main() {

Person person;

PersonExtensions* pE = (PersonExtensions*) &person;
std::cout << pE -> size() << std::endl;
std::cout << (*pE).size() << std::endl;

std::cout << sizeof(Person) << std::endl;
std::cout << sizeof(PersonExtensions) << std::endl;

return 0;

Do you think that this incorrect pointer assignment, since “Extension Method” only accessed public members of extended class & extension class don’t going to have any Field variables, can represent a problem in the future?
The size of the object are the same.