How to implement this?
Kenji Hara
k.hara.pg at gmail.com
Mon Jun 10 07:40:04 PDT 2013
On Monday, 10 June 2013 at 09:42:56 UTC, Elvis wrote:
> class A
> {
> enum TypeID = 1;
> }
> class B : A
> {
> enum TypeID = 2;
> }
>
> class C : A
> {
> enum TypeID = 3;
> }
>
> class D : B
> {
> enum TypeID = 4;
> }
>
> ...
>
>
> Could anybody shed some light on how to make these TypeIDs auto
> increment at compile time?
version(A)
{
class A
{
enum TypeID = 1;
}
template IncrementTypeID(Class)
{
class IncrementTypeID : Class
{
enum TypeID = Class.TypeID + 1;
}
}
alias B = IncrementTypeID!A;
alias C = IncrementTypeID!B;
alias D = IncrementTypeID!C;
}
version(B) // more generative way
{
template MakeContinuousClasses(int endID)
{
static if (endID > 0)
{
mixin MakeContinuousClasses!(endID - 1);
enum className = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[endID -
1];
static if (endID == 1)
enum baseClass = "";
else
enum baseClass = " : " ~
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"[endID - 2];
import std.conv : to;
mixin("class "~className~baseClass~" { enum TypeID =
"~endID.to!string~"; }");
}
}
mixin MakeContinuousClasses!4;
}
// test case
import std.traits;
pragma(msg, A.TypeID, ", ", BaseClassesTuple!A); // 1, (Object)
pragma(msg, B.TypeID, ", ", BaseClassesTuple!B); // 2, (A,
Object)
pragma(msg, C.TypeID, ", ", BaseClassesTuple!C); // 3, (B, A,
Object)
pragma(msg, D.TypeID, ", ", BaseClassesTuple!D); // 4, (C, B, A,
Object)
Kenji Hara
More information about the Digitalmars-d-learn
mailing list