Skip to content

Instantly share code, notes, and snippets.

@SirTony
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SirTony/bb0594891f54388fca7b to your computer and use it in GitHub Desktop.
Save SirTony/bb0594891f54388fca7b to your computer and use it in GitHub Desktop.
A struct that wraps both function and delegate types, allowing them to be used interchangeably.
final struct Callback( TRet = void, TArgs ... )
{
public alias TRet delegate( TArgs ) DelegateType;
public alias TRet function( TArgs ) FunctionType;
private DelegateType dg;
private FunctionType fn;
public this( DelegateType dg ) { this.dg = dg; }
public this( FunctionType fn ) { this.fn = fn; }
public typeof( this ) opAssign( DelegateType dg ) { this.dg = dg; return this; }
public typeof( this ) opAssign( FunctionType fn ) { this.fn = fn; return this; }
public TRet opCall( TArgs args )
{
static if( is( TRet == void ) )
{
if( this.dg !is null )
this.dg( args );
else if( this.fn !is null )
this.fn( args );
}
else
{
if( this.dg !is null )
return this.dg( args );
else if( this.fn !is null )
return this.fn( args );
else
return TRet.init;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment