|
Boost : |
From: Andy Glew (glew_at_[hidden])
Date: 1999-08-30 12:57:04
> Do others think that some such template base assertion approach is
> worth developing for boost? Has anyone else tried to develop
> assert() replacements?
In spades...
Unfortunately, I keep falling back to macro based assert().
Currently, I use a macro header that includes the following
assert( boolean_expression )
-- fails if expression not valid, printing location and expression
-- compiled in only under various combinations of DEBUG flag
no_assert( boolean_expression )
-- a commented out assertion
always_assert( boolean_expression )
-- an assert that is never disabled
assertf( boolean_expression, (print_fmt, values) )
-- fails if expression not valid, printing location and expression
-- and, additionally, printing the user provided message
-- compiled in only under various combinations of DEBUG flag
Similarly no_assertf() and always_assertf()
This may look familiar to some people...
if you have ever used or seen macros such as
debugf(("message to be printef'ed if debugging\n"))
then you have probably seen code derived from some
circa 1983 headers of mine -- or independent co-inventions.
Self documentating assert error messages
-----------------------------------------------
Biggest weakness of template based approaches: one of the greatest
values of assert() is that most assert macro packages, by default,
print the text of the assertion that failed. I.e. they don't just say
assertion failed at file.cc:19
but say, rather
assertion `ptr != 0' failed at file.cc:19
I.e. they are primitively self documenting.
This strongly suggests that a macro that can stringify the arguments
should be wrapped around your templates.
Better error messages
-------------------------
I personally think that such primitive messages leave a lot to be desired,
although I have encountered users who swear by them.
I frequently use assertf( exp, (printf_fmt,...) )
so that more meaningful messages can be provided
Interestingly, this might be easier to templatify than the simple assert()
with the default stringification of the macro argument.
Elaborating Error Messages
---------------------------------
The best thing about C++ error handling is that successive exception handlers
can wrap progressively more meaningful error messages around an exception
object.
E.g. level 1 says "null pointer"
level 2 says "error allocating data structure"
level 3 says "error opening database"
Therefore, if you insist on throwing exceptions, at the very least
you should provide some hook so that the caller can get a meaningful
exception string onto the stack.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk