"%s"-format template function arguments

Alex sascha.orlov at gmail.com
Sun Apr 15 12:23:55 UTC 2018


On Sunday, 15 April 2018 at 12:04:19 UTC, vladdeSV wrote:
> Hello people of D-land.
>
> In a template function, I want to format all arguments as if it 
> was an array. Se this snippet of code:
>
>     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"?
>
> Best regards,
> Vladimirs Nordholm
>
> ---
>
> P.S.
> I do not understand why only a `1` is printed in the actual 
> result.

If you define foo like that, then, you advice D to handle the 
input as separate objects. That's ok. But then, you have to 
define that you still assume, they belong together, like an array.

In this example the solution is simple:

´´´
void main()
{
	foo(1,2,3);
}

void foo(T...)(T args)
{
	import std.stdio : writefln;
	import std.range : only;

     writefln("expected: %s", [1,2,3]);
     writefln("actual: %s", args.only);
}
´´´
However, there will be problems, if the types of elements 
differs: While the template foo will be able to handle this, the 
std.range : only function won't. It assumes at least something 
common across them.

https://dlang.org/library/std/range/only.html



More information about the Digitalmars-d-learn mailing list