Eliminating code duplication for static/nonstatic functions

Kenji Hara k.hara.pg at gmail.com
Fri Sep 20 00:34:11 PDT 2013


2013/9/20 Andrei Alexandrescu <SeeWebsiteForEmail at erdani.org>

> 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).
>

Just an idea: string mixin + UDA?

  @mixin(hasState ? "" : "static")
  int method() { return 1 + _theT.method(); }

Kenji Hara
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20130920/96d02dc3/attachment.html>


More information about the Digitalmars-d mailing list