Passing refs with delegates

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Aug 3 01:12:00 PDT 2016


On 08/02/2016 07:55 PM, Mark J Twain wrote:
> It's nice to be able to pass delegates and functions as callbacks.
>
> A nice feature is something like
>
> R foo(R,Args...)(R function(Args) callback, Args args) { return
> callback(args); }
>
> There are two problems with this.
>
> One is that type deduction doesn't work. I have to explicitly specify
> the types of args. This creates a lot of verbosity. Second, I can't pass
> ref parameters. The usefulness of this method is that it sort of lets
> you pass data in and out of the callback, all defined by the user
> calling foo. Sometimes you want to pass in references to store data and
> other times you don't.
>
> Is this a bug in D's type checking system or unfinished work or simply
> nonsense?
>
> right now I pass in pointers, but that doesn't work to well for some
> types, and is messy.
>
>
>
>

I didn't know one could use 'auto ref' in this case but the following 
simple test works:

auto foo(Func, Args...)(Func callback, auto ref Args args) {
     return callback(args);
}

double bar(ref int i, int j, ref int k) {
     i = 100;
     k = 102;
     return 7.5;
}

void main() {
     int i;
     int k;
     auto a = foo(&bar, i, 2, k);
     assert(i == 100);
     assert(k == 102);
     assert(a == 7.5);
}

Ali



More information about the Digitalmars-d-learn mailing list