Eliminating code duplication for static/nonstatic functions

Simen Kjaeraas simen.kjaras at gmail.com
Fri Sep 20 08:52:55 PDT 2013


On 2013-09-20, 17:20, Andrei Alexandrescu wrote:

> On 9/19/13 1:02 PM, Andrej Mitrovic wrote:
>> On 9/19/13, Andrei Alexandrescu <SeeWebsiteForEmail at erdani.org> wrote:
>>> I'm not sure I understand how that would work.
>>
>> -----
>> module test;
> [snip]
>
> Thanks, that's the simplest and most effective. I reduced it to:
>
> struct A
> {
>      enum hasState = false;
>      private mixin template funDef()
>      {
>          void fun(int x) { writeln(x); }
>      }
>      static if (hasState)
>          mixin funDef!();
>      else
>          static mixin funDef!();
> }
>
> void main()
> {
>      A a;
>      a.fun(42);
> }
>
> I see no way to extract the scaffolding into a library.

Like this?


import std.stdio;

mixin template maybeStatic(bool isStatic, alias funDef, args...) {
     static if (isStatic) {
         static mixin funDef!args;
     } else {
         mixin funDef!args;
     }
}

struct A
{
     enum hasState = false;
     private mixin template funDef()
     {
         void fun(int x) { writeln(x); }
     }
     mixin maybeStatic!(!hasState, funDef);
}

void main()
{
     A a;
     a.fun(42);
}

-- 
   Simen


More information about the Digitalmars-d mailing list