Boost logo

Boost :

From: Howard Hinnant (hinnant_at_[hidden])
Date: 2006-07-25 13:45:00


On Jul 25, 2006, at 12:53 PM, John Maddock wrote:

>> I recommend restricting these templates to floating point types.
>> Otherwise they are overly generic, and could easily be called
>> accidently, especially isnormal, is_normal, isnorm (or whatever, C99
>> and C++0X call it isnormal).
>
> Oh, actually I *need* generic versions of these functions in order
> to make
> parts of the math toolkit I'm working on generic: at the very least
> these
> scale to pretty much anything that has numeric_limits defined,
> without that
> all you can do is assume the number is a zero or a normal: but
> that's OK too
> because most (all?) extended precision types like NTL::RR don't
> support
> infinities or NaN's anyway.
>
> Of course passing a complex number or an octonium or something
> *would* be a
> mistake, but I'm assuming that any function that makes use of isnan
> etc
> wouldn't be compatible with these anyway.

Here's the type of code one needs to defend against:

namespace Mine
{

struct Person {};

struct Female : public Person {};

bool isnormal(const Person&);

}

int main()
{
     using namespace boost; // for boost::bind (just as an example)
     Mine::Female Jane;
     bool b = isnormal(Jane);
}

I.e. the user includes boost for some reason completely unrelated to
fp-classification. He may even be ignorant of its existence. But
somehow via includes the client isn't even in control of,
boost::isnormal(T) gets included in the translation unit. It
greedily grabs the call to isnormal because it ends up being a better
match than the client's intended function (which he didn't even
realize he was overloading with a boost function).

If you can restrict your template parameter somehow (perhaps with
numeric_limits<T>::is_specialized), you can avoid accidental clients.

isnan doesn't seem so susceptible to this type of accident, but
isnormal sure does. I've been bitten by this one before (with sqrt
believe it or not).

-Howard


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