Eliminating code duplication for static/nonstatic functions
Dmitry Olshansky
dmitry.olsh at gmail.com
Fri Sep 20 02:24:44 PDT 2013
19-Sep-2013 21:10, Andrei Alexandrescu пишет:
> Consider a struct that may or may not have state depending on a type
> parameter:
[snip]
> Any ideas for a clean solution? I can't get much further than string
> mixins, which wouldn't be clean :o).
It seems like s/string/template and we are there.
This works for me:
import std.traits;
struct Static{
static int method(){ return 21; }
}
struct Instance{
int v; //so that it "hasState"
int method(){ return 12; }
}
mixin template Methods()
{
int method() { return 1 + _theT.method(); }
}
struct S(T)
{
enum hasState = FieldTypeTuple!T.length || isNested!T;
static if (hasState)
T _theT;
else
alias _theT = T;
static if (hasState)
mixin Methods!();
else{
static{
mixin Methods!();
}
}
}
void main()
{
S!Static s1;
S!Instance s2;
assert(S!Static.method() == 22);
assert(s1.method() == 22);
assert(s2.method() == 13);
assert(s1.sizeof == 1);
assert(s2.sizeof == 4);
}
--
Dmitry Olshansky
More information about the Digitalmars-d
mailing list