On 5/31/11 6:05 PM, bearophile wrote:
Nick Sabalausky:

http://www.semitwist.com/articles/EfficientAndFlexible/SinglePage/

Regarding your addGizmos() in ex6_meta_flex3_runtimeToCompileTime1.d:


void addGizmos(int numPorts, bool isSpinnable, int numGizmos) {
     // Dispatch to correct version of addGizmosTo.
     // Effectively converts a runtime value to compile-time.
     if (numPorts == 1) {
         if (isSpinnable)
             addGizmosTo!(1, true )(numGizmos);
         else
             addGizmosTo!(1, false)(numGizmos);
     } else if (numPorts == 2) {
         if (isSpinnable)
             addGizmosTo!(2, true )(numGizmos);
         else
             addGizmosTo!(2, false)(numGizmos);
     } else if (numPorts == 3) {
         if (isSpinnable)
             addGizmosTo!(3, true )(numGizmos);
         else
             addGizmosTo!(3, false)(numGizmos);
     } else if (numPorts == 5) {
         if (isSpinnable)
             addGizmosTo!(5, true )(numGizmos);
         else
             addGizmosTo!(5, false)(numGizmos);
     } else if (numPorts == 10) {
         if (isSpinnable)
             addGizmosTo!(10, true )(numGizmos);
         else
             addGizmosTo!(10, false)(numGizmos);
     } else
         throw new Exception(to!string(numPorts)~"-port Gizmo not supported.");
}


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

Why you need a type tuple? Can't you do:

foreach(np; [1, 2, 3, 5, 10])

Reply via email to