Simen kjaeraas <simen.kja...@gmail.com> wrote:

Another few that showed up now with my work on combinatorial products of ranges:

/**
Determines whether a template parameter is a type of value (alias).

Example:

----
template foo( T... ) if (allSatisfy!( isAlias, T ) {...}
----
*/
template isAlias( alias T ) {
    enum isAlias = true;
}

template isAlias( T ) {
    enum isAlias = false;
}


/**
Switches between template instantiations depending on the parameters passed.

Example:

----
alias staticSwitch( foo, 1, 2, 3 ).With callFoo;
callFoo( 2 ); // Actually calls foo!(2)( )
----
*/
template staticSwitch( alias F, T... ) if ( allSatisfy!( isAlias, T ) ) {
auto With( CommonType!T index, ParameterTypeTuple!( F!( T[0] ) ) args ) {
        switch ( index ) {
            foreach ( i, e; T ) {
                mixin( Format!( q{case %s:}, e ) );
                return F!( e )( args );
                break;
            }
        }
        assert( false );
    }
}

version( unittest ) {
    int foo( int n ) {
        return n;
    }
}

unittest {
    assert( staticSwitch!( foo, 1, 2 ).With( 2 ) == 2 );
}

The latter does currently not work, due to bug 4292, but a patch has been submitted. Granted, a simple template would work around that problem, but better to remove it at the root.

Philippe, if you or anyone else want to add any of these templates to your dranges or their own collection of templates, I would be pleased to allow it. But please do give credit.

--
Simen

Reply via email to