Boost logo

Boost :

Subject: Re: [boost] [xint] Boost.XInt formal review
From: Scott McMurray (me22.ca+boost_at_[hidden])
Date: 2011-03-15 15:16:05


On Tue, Mar 15, 2011 at 11:48, Thomas Klimpel
<Thomas.Klimpel_at_[hidden]> wrote:
>
> [...] Two of these occurrences had the form "(m%std::ptrdiff_t(n)+n)%n", which surprised me a bit. When I replaced them with "modulo(m, n)", the compiler refused to compile it. So I wrote "modulo(m, std::ptrdiff_t(n))" instead, and this compiled fine. Thinking a bit about this, I realized that the template does the right thing by refusing to compile this, whereas the "(m%n+n)%n" construct can lead to surprising results in case n is of type std::size_t.
>

Perhaps the real thing it's telling you is that you want something like this:

    template <class T>
    enable_if_c<numeric_limits<T>::is_signed, T>::type
    modulo(T m, const T& n)
    {
        m %= n;
        if (m < 0) m += n;
        return m;
    }

    template <class T>
    enable_if_c<numeric_limits<T>::is_signed, T>::type
    modulo(T m, const T& n)
    {
        m %= n;
        return m;
    }

Because if you really want modulo 4000000000, casting to ptr_diff_t
will give very strange results on LP32...

~ Scott


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk