printf() metaprogramming challenge

Alex AJ at gmail.com
Thu May 23 23:34:47 UTC 2019


> template Spec(T : byte)    { enum Spec = "%d"; }
> template Spec(T : short)   { enum Spec = "%d"; }
> template Spec(T : int)     { enum Spec = "%d"; }
> template Spec(T : long)    { enum Spec = "%lld"; }
>
> template Spec(T : ubyte)   { enum Spec = "%u"; }
> template Spec(T : ushort)  { enum Spec = "%u"; }
> template Spec(T : uint)    { enum Spec = "%u"; }
> template Spec(T : ulong)   { enum Spec = "%llu"; }
>
> template Spec(T : float)   { enum Spec = "%g"; }
> template Spec(T : double)  { enum Spec = "%g"; }
> template Spec(T : real)    { enum Spec = "%Lg"; }
>
> template Spec(T : char)    { enum Spec = "%c"; }
> template Spec(T : wchar)   { enum Spec = "%c"; }
> template Spec(T : dchar)   { enum Spec = "%c"; }
> template Spec(T : string)  { enum Spec = "%.*s"; }
>
> template Spec(T : immutable(char)*)   { enum Spec = "%s"; }
> template Spec(T : const(char)*)       { enum Spec = "%s"; }
> template Spec(T : T*)                 { enum Spec = "%p"; }

this can all be simplified:

static foreach(k,v: ["byte":"%d", "short":"%d", ...])
     mixin(`template Spec(T : `~k~`) { enum Spec = "`~v~`"; }`);

The string mixin is not necessary but easier than an aliasSeq.




More information about the Digitalmars-d mailing list