TIP: Click on subject to list as thread! ANSI
echo: c_plusplus
to: BOB STOUT
from: JERRY COFFIN
date: 1997-07-14 10:00:00
subject: Signs of numbers

On (13 Jul 97) Bob Stout wrote to Kurt Kuzba...
 BS>   The bottom line is that a single function...
 BS> int sgn(double x)
 BS> {
 BS>       if (x > 0.0)
 BS>             return 1;
 BS>       if (x < 0.0)
 BS>             return -1;
 BS>       else  return 0;
 BS> }
 BS> ...would work just fine in C, but in C++, either a template
 BS> implementation or overladed functions would be best.
I think in this case a templated function is preferrable to an
overloaded function:
template
int sign(const T &x) {
    if ( x > 0)
        return 1;
    else if ( x < 0)
        return -1;
    return 0;
}
This should work for any type for which comparison to 0 and having a
sign makes sense.  The only problem that might arise would be things
like smart pointers that define comparison to 0 only in terms of equal
and not equal, rather than less than/greater than.  In particular, I've
seen a few that would do things like saying a pointer was both less than
AND greater than 0, as long as it wasn't equal to 0.  In this case,
the "sign" you obtained for that pointer type wouldn't depend on the
pointer itself, but on the order in which you did the comparisons.
These might handle the comparison by defining a conversion of int to the
smart pointer, then compare the two, in which case the comparison might
not work very well.  Strongly preferrable is for the smart pointer to
explicitly define the comparison operators it supports (==(int) and
!=(int)) and make the conversion from int to smart pointer explicit,
meaning you'd have to use `T(0)' to get 0 converted to a pointer.
Unfortunately, there are still quite a few compilers around that don't
support the explicit keyword.
    Later,
    Jerry.
... The Universe is a figment of its own imagination.
--- PPoint 1.90
---------------
* Origin: Point Pointedly Pointless (1:128/166.5)

SOURCE: echomail via exec-pc

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.