www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Templates and writing variable number of arguments

reply Andre Polykanine via Digitalmars-d-learn writes:
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!

-- 
With best regards from Ukraine,
Andre
Skype: Francophile
Twitter:  m_elensule; Facebook: menelion
My blog: http://menelion.oire.org/
Aug 23 2015
parent ted <foo bar.com> writes:
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!
 
Aug 23 2015