Variable arguments with file and line information?
Jonathan M Davis
jmdavisProg at gmx.com
Sat Nov 16 15:55:32 PST 2013
On Sunday, November 17, 2013 00:09:53 Namespace wrote:
> On Saturday, 16 November 2013 at 22:57:35 UTC, Namespace wrote:
> > Hi.
> > Is it possible to write something like that?
> > ----
> > void error(Args...)(string msg, Args args, string file =
> > __FILE__, size_t line = __LINE__) { ... }
> > ----
> > ?
> > Currently not, but how could it be done? I wont like to write:
> > ----
> > error(format(msg, args));
> > ----
> >
> > Thanks in advance. :)
>
> It is always surprising how quickly one has found its own
> solution, after you have posted here... :)
>
> ----
> import std.stdio;
> import std.string : format;
>
> template error(string file = __FILE__, size_t line = __LINE__,
> Args...) {
> void error(string msg, Args args) {
> static if (args.length != 0)
> msg = .format(msg, args);
>
> writeln(.format(msg ~ ". In file %s on line %d.", file, line));
> }
> }
>
> void main()
> {
> error("hallo");
> error("Hallo %s.", "du da");
> }
> ----
If you're dealing with variadic arguments, then making the file and line number
be template arguments is really your only solution. However, I must warn you
that that will result in a new template instantation _every_ time that you use
error, because the file and line number are always going to be different unless
you call the function multiple times on the same line). So, this approach is
pretty much guaranteed to generate template bloat. That may be acceptable, but
I'd personally suggest trying to find a different way to go about solving the
problem unless error is not going to be called very often - e.g. force the
caller to call format when creating the message rather than supporting
variadic arguments directly in error.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list