www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - "Best" way of handling a receive()d message with a class instance.

reply "Francesco Cattoglio" <francesco.cattoglio gmail.com> writes:
Suppose that I receive a message, but instead of defining a 
function inside the receive() block, I want to call a member of a 
class instance. (This is useful to me for several reasons). Right 
now my code looks like:

class Handler {
auto handle() {
     return (string msg) {
         writeln("received: ", msg, " count: ", i);
     }; // this ';' ends the return statement
} // handle()
private:
     i;
}

//somewhere inside main
auto handler = new Handler;
receiveTimeout( dur!"seconds"(1),
                 handler.handle
               );

It works, but I must say I'm not even sure about what the hell I 
am doing :D
If I got it correctly, I'm calling a function that returns a 
delegate, which is used by the receiveTimeout() somehow to 
dispatch the message (and everything is in some way decided at 
compile time, I believe).
Does this ugly piece of code make any sense? Should I rework it?
Jan 23 2014
parent reply "Francesco Cattoglio" <francesco.cattoglio gmail.com> writes:
Sorry, MY BAD!

You can just write
auto handler = new Handler;
receive(&handler.MyFunc);

Somehow when I tried this before it failed to compile, and I 
thought I had to go through loops for achieving this.
Jan 23 2014
parent "Meta" <jared771 gmail.com> writes:
On Thursday, 23 January 2014 at 16:00:30 UTC, Francesco Cattoglio 
wrote:
 Sorry, MY BAD!

 You can just write
 auto handler = new Handler;
 receive(&handler.MyFunc);

 Somehow when I tried this before it failed to compile, and I 
 thought I had to go through loops for achieving this.
It's also useful to mention that in this code here: auto handler = new Handler; receiveTimeout( dur!"seconds"(1), handler.handle ); The expressions handler.handle is actually invoking the method handle(). This is due to parentheses being optional in D, which means that even the function name without the parentheses is a valid function call. I don't know if you knew that or not, just in case you didn't.
Jan 23 2014