Prettiful error messages with templates

Simen Kjaeraas simen.kjaras at gmail.com
Sun May 4 14:53:22 PDT 2008


I'm currently using this somewhat verbose approach to template error  
messages:

debug
{
   int opAdd(U, int line = __LINE__, string file = __FILE__)(U args)
   {
     static if (__traits(compiles, somethingHere)) // check if this  
template should have been instantiated at all
     {
       pragma(msg, "Failed instantiating template in file " ~ file ~ " on  
line " ~ toString(line)); // for a more prettiful error message. Could  
easily put this in the assert
       static assert(0);
     }
     // Do actual work here. Don't use line or file arguments.
   }
}
else
{
   int opAdd(U)(U args)
   {
     // Do actual work here.
   }
}

Now, what are the problems with this approach?

1. It is rather verbose.
2. Code duplication.
3. Template bloat for the debug version. For every time + is used, a new  
instantiation is created. I have duplicated the code to avoid this in  
release builds.
4. toString(int) is not CTFE-compatible.

Good things:

It gives exact error messages, telling the user what went wrong and where.

So, what do I want?

An easier way of doing this. If it weren't for #3 (which might be a  
limitation of the linker or compiler), I could avoid the code duplication,  
so I guess that's the biggest problem.

Any ideas?

-- Simen


More information about the Digitalmars-d-learn mailing list