On Wed, Oct 30, 2013 at 08:41:32AM +0000, Andrew Haley wrote:
> On 10/30/2013 08:34 AM, Ondřej Bílka wrote:
>
> >>
> > The reasons of adding builtins is performance. Without that one can
> > write a simple template to generically check overflows like
> >
> > template <class C> class overflow {
> > public:
> > C val;
> > overflow <C> operator + (overflow <C> &y) {
> > overflow <C> ret;
> > if (val > 0 && y.val > 0 && val + y.val < val)
> > throw std::overflow_error();
> > /* ... */
> > ret.val = val + y.val;
> > return ret;
> > }
> > /* ... */
> > };
>
> How is that going to work? The compiler can simply eliminate this line:
>
> if (val > 0 && y.val > 0 && val + y.val < val)
> throw std::overflow_error();
>
> because it knows that the guard is always false. I suppose it could be
> compiled with -fwrapv.
>
Example code, only to show structure not working implementation. Real
code is uglier you would need add traits and do comparison like
template <> class limits <int> {
const int min = INT_MIN;
const int max = INT_MAX;
}
...
overflow <C> operator + (overflow <C> &y) {
overflow <C> ret;
limits <C> limit;
if (val > 0 && y.val > 0 && limit.max - a.val < val)