Create a delegate function

Prudence via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Sep 5 11:00:52 PDT 2015


I have code setup in such a way that I call a user defined 
function, e.g.,

void myFunc(Data d)
{
....
}

myFunc has to be passed to the main code using something like

void SetFunc(void function(Data) func) { ... func(myData); }

What I would like to do is, instead of having to pass data to 
myFunc(and use the type Data in all the function types), is to 
sort of create a delegate:

what I want to do:

void myFunc()
{
       this.d;  // Ok, because somehow this = Data;
}

then, of course,

void SetFunc(void delegate() func) { func.context = myData; 
func(); }




void delegate() dg =
{
	auto t = this;
	return;
};

doesn't even work because this is not defined.


My guess this is impossible without compiler support.

effectively though, I don't see why we can't use this(because 
myFunc is being executed in a context, I simply want to set it to 
the right one so that the user can take advantage of it... 
instead of having to pass an argument instead.


Any ideas how to do this? It seems we can't actually create 
"delegate objects" but only delegate pointers? (simply because of 
the restrictions the compiler places on *this*. (can't be used 
outside of a context, even though we can always guarantee it is 
in a context)

How bout a new syntax for such concepts?

void delegate!T(...) dg
{

}

// identical to

void dg(T this, ...)
{

}


Hence, to call dg, we have to pass it a "this" object... hence it 
has a context. They can be called just like functions. dg(myData, 
...);




More information about the Digitalmars-d-learn mailing list