On Tuesday, 26 January 2021 at 14:15:25 UTC, frame wrote:
On Tuesday, 26 January 2021 at 04:39:07 UTC, Jack wrote:
note the body is the same, what changes is the base class. I'd
like to avoid repeating myself when the body is the same and
only the base class changes.
You would have to call it with correct instantiation like
alias Foo = C!(A!bool);
Of course T!MyType would not work but I don't think you want
that anyway.
It very depends on the use-case but just use a mixin where you
can pass any type you want from template constructor if you
don't want to repeat yourself:
class MyType {
}
class A {
}
class B {
}
template base(T) {
static if (is(T : A)) {
bool doSomething() {
return true;
}
}
else static if (is(T : B)) {
bool doSomething() {
return false;
}
}
else {
void doSOmethingElse() {
}
}
}
class C(T1, T2) {
mixin base!T2;
T1 whatever() {
return new T1;
}
}
alias Foo = C!(MyType, A);
alias Baa = C!(MyType, B);
Thank you! I find this approach rather elegant. Ability to pick
the method to be part of the class' body without macros is really
great.