|
Boost : |
From: Kevlin Henney (kevlin_at_[hidden])
Date: 2000-12-08 05:33:09
In message <200012072215.OAA28451_at_[hidden]>, Jesse Jones
<jesjones_at_[hidden]> writes
>>It should be a runtime failure rather than a debugging issue as there
>>are many conversions that cannot be conveniently checked ahead of use --
>>to do so would require near duplication of all the code that makes up
>>numeric_cast :->
>
>This is certainly true some of the time, but I think I'd quibble with the
>"many" part. :-)
I wouldn't ;-)
>>One could also argue that there would be little point in having
>>numeric_cast if it trapped only in debug mode. Might as well use
>>static_cast and see if you get the right results in your unit tests --
>>if not, you have a conversion bug! ;-)
>
>There's lot of code that really can't be unit tested very effectively.
>For example, 3/4 of my numeric casts are probably in my low level Mac GUI
>code where I have to convert ints to shorts. It's hard to unit test a
>window or a checkbox...
In which case, it seems quite clear that what you need here is a
runtime-checked conversion not a debug statement. If you cannot
adequately path test the code, then assume the worst. numeric_cast in
its current form is the correct tool for the job, from the sounds of it.
>>And finally, there is the point that, as a checked cast, numeric_cast is
>>consistent with the existing language. The example it follows closest is
>>dynamic_cast<T &>.
>
>Hmm, I believe you're right. You leave me no alternative but to fall back
>on C++'s famed obsession with performance. :-) So, I guess my question
>is, just how badly will an inline function that throws screw up a
>compiler's code gen?
If you are doing GUI work I suspect that this would be one of those
'optimisations' that amounts to a drop in the ocean :->
Seriously, I think what you are after is something different.
numeric_cast performs a runtime-checked conversion, period. Although it
may be used to assist debugging, it is not the same kind of tool as
assert. However, if that is what you want, then rather than make
numeric_cast fulfil a role it was not intended for (or fulfil two
separate roles), use the following macro:
#ifndef NDEBUG
#define ASSERT_NO_THROW(expr) \
try \
{ \
expr; \
} \
catch(...) \
{ \
... // display messages or whatever
abort(); \
}
#else
#define ASSERT_NO_THROW(expr) void(0)
#endif
And use as follows:
ASSERT_NO_THROW(numeric_cast<T>(i));
T t = static_cast<T>(i);
____________________________________________________________
Kevlin Henney phone: +44 117 942 2990
Curbralan Limited mobile: +44 7801 073 508
mailto:kevlin_at_[hidden] fax: +44 870 052 2289
http://www.curbralan.com
____________________________________________________________
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk