SirTony
2/9/2015 - 3:33 PM

A struct that wraps both function and delegate types, allowing them to be used interchangeably.

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;
        }
    }
}