Eliminating code duplication for static/nonstatic functions
Andrei Alexandrescu
SeeWebsiteForEmail at erdani.org
Sat Sep 21 04:05:08 PDT 2013
On 9/20/13 8:52 AM, Simen Kjaeraas wrote:
>> 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);
> }
>
This is nice. Works with shared, too.
Andrei
More information about the Digitalmars-d
mailing list