[Article Submission] Have Your Efficiency, and Flexibility Too

Timon Gehr timon.gehr at gmx.ch
Tue May 31 05:11:40 PDT 2011


bearophile wrote:
> ...
> A shorter way to write it:
>
> void addGizmos(int numPorts, bool isSpinnable, int numGizmos) {
>     foreach (np; TypeTuple!(1, 2, 3, 5, 10))
>         if (numPorts == np) {
>             foreach (b; TypeTuple!(true, false))
>                 if (isSpinnable == b)
>                     addGizmosTo!(np, b)(numGizmos);
>             return;
>         }
>
>     throw new Exception(text(numPorts) ~ "-port Gizmo not supported.");
> }
>
> Bye,
> bearophile

Nice, but isSpinnable is always checked twice with your approach. Better:

void addGizmos(int numPorts, bool isSpinnable, int numGizmos) {
    foreach (np; TypeTuple!(1, 2, 3, 5, 10))
        if (numPorts == np) {
                if (isSpinnable) addGizmosTo!(np, true)(numGizmos);
                else addGizmosTo!(np, false)(numGizmos);
            return;
        }

    throw new Exception(text(numPorts) ~ "-port Gizmo not supported.");
}

@Article: A very good read, it does not get boring even though it is quite long. I
like it.

Small nitpick:
mixin(declareInterface("IGizmo", "Gizmo!(numPorts, isSpinnable)"));

It seems like this should be a mixin template, not a string mixin. Also you
wouldn't normally want to specify ThisType. Use typeof(this):

mixin template declareInterface(string interfaceName){
    mixin(`enum _this_implements_interface_`~interfaceName~`=true;`);
    mixin(`static assert(
               is`~interfaceName~`!(typeof(this)),

               "This type fails to implement `~interfaceName~`"
           );`
    );
}

and then you do just:
mixin declareInterface!"IGizmo";


Timon


More information about the Digitalmars-d mailing list