www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Passing refs with delegates

reply Mark "J" Twain <Juckleberry Twain.com> writes:
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.
Aug 02 2016
parent reply =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
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
Aug 03 2016
parent Mark "J" Twain <Juckleberry Twain.com> writes:
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.
Aug 03 2016