Extend types with free functions as methods
Quirin Schroll
qs.il.paperinik at gmail.com
Sun Dec 19 21:53:09 UTC 2021
Someone asked about that and I cannot find the thread anymore.
The goal was to write something so that one can pass an object of
some type to a function that expects it to have certain methods.
Sometimes, the functionality of the methods can be implemented
using free functions, but if the function to be called lies in
another module, how would it know of those free functions? UFCS
only works with the functions in scope.
I tried to implement that and got some results. I called it
`subjoin`.
For example, you'd write it as `func(arg.subjoin!(f1, f2))` when
`f1` and `f2` are "missing" as methods of `arg`.
Have a look at the code: https://run.dlang.io/is/7dx1F1
```D
void rangeExpectingFunction(Range)(Range range)
{
import std.stdio;
for (; !range.empty; range.popFront)
writeln(range.front);
}
void main()
{
import std.range.primitives : empty, front, popFront;
[ 1, 2, 3 ].subjoin!(empty, front,
popFront).rangeExpectingFunction;
}
```
I hope the one asking for this finds this or is lead here by
others.
More information about the Digitalmars-d
mailing list