printf() metaprogramming challenge

Les De Ridder les at lesderid.net
Thu May 23 22:56:31 UTC 2019


On Thursday, 23 May 2019 at 22:48:33 UTC, Jonathan Marler wrote:
> It uses mixin, so not pretty, but it works...

Similar solution:

--- printf.d	2019-05-24 00:48:44.840543714 +0200
+++ printf_s.d	2019-05-24 00:52:47.829178613 +0200
@@ -1,13 +1,12 @@
  import core.stdc.stdio : printf;

-template Seq(A ...) { alias Seq = A; }
-
  int dprintf(string f, A ...)(A args)
  {
      enum Fmts = Formats!(A);
      enum string s = formatString(f, Fmts);
+    alias args_ = Args!(args);
      __gshared const(char)* s2 = s.ptr;
-    return printf(Seq!(s2, args[0..2], args[2..4]));
+    mixin( q{return printf(s2, } ~ args_ ~ q{);} );
  }

  template Formats(T ...)
@@ -42,6 +41,22 @@
  template Spec(T : const(char)*)       { enum Spec = "%s"; }
  template Spec(T : T*)                 { enum Spec = "%p"; }

+template Spec(T : string)  { enum Spec = "%.*s"; }
+
+template Args(A ...)
+{
+    static if (A.length == 0)
+	enum Args = "";
+    else static if (A.length == 1)
+	enum Args = Arg!(A[0]);
+    else
+	enum Args = Arg!(A[0]) ~ ", " ~ Args!(A[1 .. A.length]);
+}
+
+template Arg(alias string arg) { enum Arg = 
"cast(int)"~arg.stringof~".length,"~arg.stringof~".ptr"; }
+
+template Arg(alias arg) { enum Arg = arg.stringof; }
+
  /******************************************
   * Replace %s format specifiers in f with corresponding 
specifiers in A[].
   * Other format specifiers are left as is.



More information about the Digitalmars-d mailing list