Fun With Generics, Class Templates and Static Ifs

eris jvburnes at gmail.com
Thu Jun 4 12:55:34 PDT 2009


Denis Koroskin Wrote:

> On Thu, 04 Jun 2009 20:35:13 +0400, eris <jvburnes at gmail.com> wrote:
> 
> > Greetings D People
> >

> > ---
> >
> 
> Your ideas are right, but code smells a bit :) Just a few comments:
> 
> - what's len? It's never initialized. There's no need to have it, because  
> you can use "members.length" property instead.
> Second, make sure you make your fields private.
> 

Hehe.  Thanks.   Sure.  This code wasn't meant as a final form in any sense.  As you and bearophile point out, it's better to use a more sophisticated way of indicating or including the alternate storage behavior.  You're correct.  Len isn't initialized, and the current form of the algo already corrects this.
 
> - I'd use an enumeration to specify minimum or maximum:
> enum StorePolicy { Minumum, Maximum }
> class Rank(T, StorePolicy policy) { ... }
> 
> - Don't use "members[len-1]", use "members[$-1]" instead.
> 

Good idea on storage policy.  Much better than a -1,0,+1 hack and much more readable.  

> - I don't see any reason not to declare "i" inside a for loop ("bool  
> submit(T value)" method):
> 
> for (int i = 0; ...) { ... }
> 

Because I need its value outside the loop after break.   The code you see is just enough to get the compiler to accept it and doesn't show algorithm details.

> - There is no need for a loop at all!
>

Actually the loop implements a single insertion pass.  The object is optimized for access frequency.
 
> bool submit(T value) {
>      static if (policy == StorePolicy.Minimum) {
>          if (members[$-1] < value) {
>              return false;
>          }
>          members[$-1] = value;
>     } else {
>          if (members[0] > value) {
>              return false;
>          }
>          members[0] = value;
>      }
> 
>      bubbleSort(members);
>      return true;
> }
> 
> Alternative implementation (should be slightly faster):
> 
> bool submit(T value) {
>      static if (policy == StorePolicy.Minimum) {

Yep.  Thanks.   I've implemented an algo similar to yours and optimized for a slightly different performance profile.

> > Is there any way to parameterize the alias statement so I can pass the  
> > type of the generic I want?
> >
...
> 
> It is done slightly different:
> 
> template MinRank(T) {
>      alias Rank!(T, -1) MinRank;
> }
> 
> template MaxRank(T) {
>      alias Rank!(T, 1) MaxRank;
> }

Cool.  Exactly what I needed.  Thanks to you and Bearophile.





More information about the Digitalmars-d mailing list