Share Pastebin
Guest
Public paste!

Nayruden

By: a guest | Nov 24th, 2008 | Syntax: D | Size: 1.10 KB | Hits: 63 | Expires: Never
Copy text to clipboard
  1. import tango.io.Stdout;
  2.  
  3. // Converts a function to a delegate. Stolen from http://dsource.org/projects/tango/ticket/1174
  4. // Note that it doesn't handle ref or out though
  5. R delegate(T) toDg(R, T...)(R function(T) fp) {
  6.     struct dg {
  7.         R opCall(T t) {
  8.             return (cast(R function(T)) this) (t);
  9.         }
  10.     }
  11.     R delegate(T) t;
  12.     t.ptr = fp;
  13.     t.funcptr = &dg.opCall;
  14.     return t;
  15. }
  16.  
  17. class SimpleCallback(R, P...)
  18. {
  19.         alias R delegate(P) callbacktype;
  20.         alias R function(P) function_callbacktype;
  21.        
  22.         private callbacktype[] callback_list;
  23.        
  24.         typeof( this ) opCatAssign( in callbacktype callback )
  25.         {
  26.                 callback_list ~= callback;
  27.                 return this;
  28.         }
  29.        
  30.         typeof( this ) opCatAssign( in function_callbacktype callback )
  31.         {
  32.                 auto dg = toDg!(R, P)( callback );
  33.                 return this ~= dg;
  34.         }
  35.        
  36.         R emit( P p )
  37.         {
  38.                 static if ( !is( R == void ) )
  39.                         R last;
  40.  
  41.                 foreach( callback; callback_list )
  42.                 {
  43.                         static if ( !is( R == void ) )
  44.                                 last = callback( p );
  45.                         else
  46.                                 callback( p );
  47.                 }
  48.                
  49.                 static if ( !is( R == void ) )
  50.                         return last;
  51.         }
  52.        
  53.         alias emit opCall;
  54. }