Variable arguments with file and line information?
Jonathan M Davis
jmdavisProg at gmx.com
Sun Nov 17 12:47:17 PST 2013
On Sunday, November 17, 2013 20:11:20 Rob T wrote:
> On Saturday, 16 November 2013 at 23:55:47 UTC, Jonathan M Davis
> wrote:
> [...]
>
> > e.g. force the
> > caller to call format when creating the message rather than
> > supporting
> > variadic arguments directly in error.
> >
> > - Jonathan M Davis
>
> OK, how about this implementation?
>
> string msg( S : string, T... )( S a_Msg, T a_Args )
> {
> if ( a_Args.length != 0 )
> a_Msg = std.string.format(a_Msg, a_Args);
> return a_Msg;
> }
Why bother with this? Just use format directly. As written, msg is a useless
wrapper function for format.
> void error(lazy string a_Msg, string file = __FILE__, size_t line
> = __LINE__)
> {
> auto v_Msg = a_Msg();
> writeln(.format(v_Msg ~ ". In file %s on line %d.", file,
> line));
> }
And as error is currently written, making the message lazy is pointless and
increases overhead. lazy is only valuable if that parameter might not be used
(e.g with the message to enforce). Also, if you're going to use a format
string, you should use writefln rather than calling format and passing the
result to writeln. It's almost certainly less overhead to call writefln.
> void main()
> {
> error(msg("hallo") );
> error(msg("Hallo %s.", "du da") );
>
> // I think this looks a whole lot better
> msg("hallo").error;
> msg("Hallo %s.", "du da").error;
>
> }
>
> It works, but still would be convenient if there was another more
> simpler way of getting the job done, also if it were more
> obvious. Once it's done though, it's rather nice I think.
It would be nice if we could get __FILE__ and __LINE__ to work as function
arguments to variadic functions, but for now, that just isn't possible.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list