better assertions and __FILE__ (compile time functions)

Bruce Adams whycantthis at stupidreaderrememberme.com
Fri Aug 24 17:31:40 PDT 2007


Chris Nicholson-Sauls Wrote:
> 
> Try this...
> 
> void assertEqual (T) (T actual, T expected, char[] file, uint line) {
>    if (actual != expected) {
>      writeln("Equality assertion failed.");
>      writefln("  actual:   '%s'", actual);
>      writefln("  expected: '%s'", expected);
>      _d_assert(file, line);
>    }
> }
> 
> template MAssertEqual (alias actual, alias expected) {
>    const MAssertEqual =
>      `assertEqual(`
>      ~actual.stringof~
>      `, `
>      ~expected.stringof~
>      `, __FILE__, __LINE__);`
>    ;
> }
> 
> unittest {
>    int var5 = 1;
>    int var6 = 2;
> 
>    mixin(MAssertEqual!(var5, var6)); // -> assertEqual(var5, var6, __FILE__, __LINE__);
> }
> 
> Note: Untested.
> 
> -- Chris Nicholson-Sauls

That doesn't work, but this does:

template MAssertEqual (alias actual, alias expected) {
   const AssertEqual =
     `assertEqual!(` ~typeof(actual).stringof  ~`)(`
     ~actual.stringof~
     `, `
     ~expected.stringof~
     `, cast(char[])(__FILE__), __LINE__);`
   ;
}

So problem solved. 
I'm not sure why template type deduction isn't working here (a D2.0 issue?), but thanks anyway. I can now run away and write Dunit if someone hasn't already done it. Of course, if they had and I knew about it I probably wouldn't have started this thread. Thanks, I've learned a bit more useful template meta foo.

Regards,

Bruce


More information about the Digitalmars-d-learn mailing list