Trouble creating a formatted assert wrapper

Nick Treleaven invalid at example.net
Mon Sep 3 05:51:46 PDT 2012


On 02/09/2012 20:31, timotheecour wrote:
>>>> void myAssert(int line = __LINE__, string file = __FILE__,
>>>> Args...)(lazy bool condition, lazy Args args) {
>
> Won't that create "template code bloat" ? Ie everytime myAssert is used
> a new function is created.
...
> Another option is to use a lazy tuple argument inside myAssert instead
> of variadic arguments, which allows to pass line and file AFTER, without
> template bloat.

Do you mean:

myAssert(condition, tuple("%d", 5));

That might be useful if myAssert was more complex than just wrapping 
format(), but in this case it doesn't seem much better.

Peter Alexander's solution seems good, i.e. using the compile-time 
default arguments but with the body forwarding to a non-template function:

myAssertBody(condition, format("Assertion failed @ %s:%d: ", file, line, 
args));

Presumably the compiler can then optimize out each myAssert instantiation.

> A related question:
> In C++ we can stringify arguments and use it to provide informative
> asserts without duplicating code specifying a string version of the
> condition:
> #define assert( isOK ) ( (isOK) ? (void)0 :
> (void)myAssert(#isOK,__LINE__,__PRETTY_FUNCTION__, __FILE__) )
>
> Likewise for related quick debug functions:
> #define DEBUG(val) myDEBUG(#val,val)
>
> There seems to be no way of doing this currently (besides the ugly
> mixin(myAssertString("i==0")) which would parse the condition at CT).

Maybe we could have something like:

void fun(bool condition, string expr = __STRINGIFY(condition));

fun(i==0); // expr = "i==0"


More information about the Digitalmars-d mailing list