Eliminating code duplication for static/nonstatic functions

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Sep 19 10:10:43 PDT 2013


Consider a struct that may or may not have state depending on a type 
parameter:

struct S(T)
{
   enum hasState = FieldTypeTuple!T.length || isNested!T;
   static if (hasState)
     T _theT;
   else
     alias _theT = T;
   ...
}

This is really nice because I don't bloat S unnecessarily and I get to 
use _theT.method() uniformly whether or not it's the type itself or the 
data member.

The duplication problem appears when S itself must define a method that 
should be static or nonstatic depending on the existence of state. Consider:

struct S(T)
{
   ... continued from above ...
   if (hasState)
     int method() { return 1 + _theT.method(); }
   else
     static int method() { return 1 + _theT.method(); }
}

In the general case the body of S!T.method() may be of course larger, 
which makes for a nasty duplication - essentially all but the "static" 
keyword must be duplicated.

Any ideas for a clean solution? I can't get much further than string 
mixins, which wouldn't be clean :o).


Thanks,

Andrei


More information about the Digitalmars-d mailing list