"%s"-format template function arguments

ag0aep6g anonymous at example.com
Sun Apr 15 12:22:30 UTC 2018


On 04/15/2018 02:04 PM, vladdeSV wrote:
>      foo(1,2,3);
> 
>      void foo(T...)(T args)
>      {
>          writefln("expected: %s", [1,2,3]);
>          writefln("actual: %s", args);
>      }
> 
> The code above will output
> 
>      expected: [1, 2, 3]
>      actual: 1
> 
> How would I go on about to print all the arguments as I expected it, 
> using "%s"?

     writefln("%s", [args]);

Or avoiding the allocation:

     import std.range: only;
     writefln("%s", only(args));

You could also change the `args` parameter to give you a stack-based array:

     void foo(T)(T[] args ...)
     {
         writefln("%s", args);
     }

[...]
> P.S.
> I do not understand why only a `1` is printed in the actual result.

This:

     writefln("actual: %s", args);

becomes this:

     writefln("actual: %s", args[0], args[1], args[2]);

So there are three arguments after the format string. The %s placeholder 
only refers to the first one. The others are ignored.


More information about the Digitalmars-d-learn mailing list