Templates and writing variable number of arguments

ted via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Aug 23 14:46:09 PDT 2015


try replacing:
    final void output(T)(string text, T params...) const {
with
     final void output(T...)(string text, T params) const {


Andre Polykanine via Digitalmars-d-learn wrote:

> Hi everyone,
> It's me again.
> Now  I'm  struggling  with  the  `output` member function which should
> output  a  string  either  to  stdout  or  to a file, depending on the
> parameter.
> However,  I would like it to work like `writefln` with variable number
> of arguments:
> output("Hello %s!", "world"); // should be OK
> output("%s  %s:  %s  %d  times",  "I", "say", "Hello world!", 500); //
> Should also be OK
> 
> Here is my code:
> 
>         final void output(T)(string text, T params...) const {
>                 if (this.outFile == "") {
>                         writefln(text, params);
>                 } else { // Output to a file
>                         auto f = File(this.outFile, "w");
>                         try {
>                                 f.writefln(text, params);
>                         } catch(Exception e) {
>                                 writefln("Unable to write to %s: %s",
>                                 this.outFile, e.msg);
>                         }
>                 }
>         }
>         
> And the compiler says it can't deduce the type of arguments.
> What am I doing wrong here?
> Maybe, I don't need such a function and all and there is a way to make
> it more elegant?
> Thanks!
> 



More information about the Digitalmars-d-learn mailing list