UFCS with implicit "this" ?

cy via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Aug 8 22:13:44 PDT 2016


I really like UFCS, which is to say, defining functions outside 
the class/struct to operate on it, but you can still say 
object.function(...) and it'll get rewritten into 
function(object,...).

Only sticky point is the convenience of "this". Like I can go

struct A {
	bool a;
	bool b;
	bool c;
	bool d;
	bool foo() {
		return a && b || c && !d;
	}
}

But if I try do do the same thing with "bool bar(A object)" I end 
up with this:

bool bar(A object) {
	return object.a && object.b || object.c && !object.d;
}

My example is a bit contrived, but it occurred to me how neat it 
would be if we could just specify "implicit" objects in our 
current scope. Like I was messing with an RGB and an HSL object, 
and I ended up having things like:

hsl.saturation = (max(rgb.r,rgb.g,rgb.b) - 
min(rgb.r,rgb.g,rgb.b)) / (2 - max(rgb.r,rgb.g,rgb.b) - 
min(rgb.r,rgb.g.rgb.b))

when I wanted something more like this:

saturation = (max(r,g,b) - min(r,g,b)) / (2 - max(r,g,b) - 
min(r,g,b)

Is there any way to do that in D? They don't let you use "alias 
this rgb" for a function scope, only a type's scope, so I guess 
it isn't possible?

I mean, aside from making an inner structure to the function, and 
copying the object by value... that's even more confusing than 
worth the convenience.


More information about the Digitalmars-d-learn mailing list