UFCS functions with both pointers and refs
Q. Schroll
qs.il.paperinik at gmail.com
Thu Dec 17 15:12:05 UTC 2020
On Tuesday, 15 December 2020 at 20:38:04 UTC, Dave P. wrote:
> The use case would be to define extension methods on a struct
> outside of where the struct is defined. The extension method
> mutates the state of the struct, so I want to ensure I am
> modifying the original struct and not a copy. If it’s a method
> and I call it on a pointer to the struct, the pointer will get
> auto-dereferenced and everything is great. So my question is
> that if I want an extension method as a free function, do I
> have to write both the version whose first argument is a
> pointer to the struct and the version whose first argument is a
> ref, or is there some keyword or other technique so that the
> pointer gets auto-dereferenced the same way as if it were a
> method. It sounds like the answer is no and I have to write a
> version that just dereferences the pointer and calls the ref
> version.
Now it's coming together.
The easiest way to do this is using an overload taking a `ref`
(non-pointer) value and another taking a pointer (by copy, I
guess).
R f(ref T value, Ts args) { /* doing the actual work */ }
R f(T* ptr, Ts args) { f(*p, args); } // manually dereference
You cannot get around doing the actual `f`, and the addition
isn't that big. I think that's the best solution unless you have
to deal with non-copyable types among Ts. Then you need to
forward those properly.
I couldn't really do better using one template instead of this
simple overload. (Certainly a template can be made, but it is
clearly not the better solution.)
More information about the Digitalmars-d-learn
mailing list