Accessing __FILE__ and __LINE__ of caller in combination with varargs?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 15 17:03:59 PDT 2016


On Friday, April 15, 2016 20:52:42 WebFreak001 via Digitalmars-d-learn wrote:
> On Friday, 15 April 2016 at 20:43:08 UTC, pineapple wrote:
> > I've written a very handy assertf method whose signature looks
> > like this:
> >
> > void assertf(Args...)(lazy bool condition, in string message,
> > Args args)
> >
> > But I'd also like to access the caller's file and line to use
> > them in constructing a thrown AssertError, and I'm stumbling on
> > how I can get that information where it needs to go. Help?
>
> void assertf(string file = __FILE__, size_t line = __LINE__,
> Args...)(lazy bool condition, in string message, Args args) {

Yes, you can do that, but do _not_ do that unless you really have no other
choice. What you need to realize is that because the file and line number
arguments will be unique for every call to this function, it will generate a
new instantiation of it _every_ time it is called. So, you're going to get a
lot of code bloat. There are rare cases where such bloat would be
acceptable, but in the general case, it's a terrible thing to do. This
particular case might be acceptable given how short it is, but in general,
using __FILE__ or __LINE__ as template arguments should be avoided like the
plague.

>      debug {
>          if (!condition) {
>              writeln(format(message, args) ~ format(" in %s:%s",
> file, line));
>              throw new AssertError();
>          }
>      }
> }

Also, to nitpick your exact implementation, debug blocks and assertions
aren't even vaguely related. debug blocks are used with the -debug flag with
the intention of being used for printing out additional debug information
(and getting around restrictions with pure with those messages while you're
at it). They have nothing to do with -release, which is what controls
assertions. What you really want to be doing is to use version(assert), not
debug.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list