Thread overview | |||||
---|---|---|---|---|---|
|
August 03, 2016 Passing refs with delegates | ||||
---|---|---|---|---|
| ||||
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. |
August 03, 2016 Re: Passing refs with delegates | ||||
---|---|---|---|---|
| ||||
Posted in reply to Mark "J" Twain | 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
|
August 04, 2016 Re: Passing refs with delegates | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ali Çehreli | On Wednesday, 3 August 2016 at 08:12:00 UTC, Ali Çehreli wrote:
> On 08/02/2016 07:55 PM, Mark J Twain wrote:
>>[...]
>
> 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
Interesting, it might just do! Thanks.
|
Copyright © 1999-2021 by the D Language Foundation