-=> Quoting Javier Kohen to Kurt J. Tischer
JK> // You'd maybe like to template this f()
JK> int foo(int num)
JK> {
JK> if (num) {
JK> if (num > 0) {
JK> return 1;
JK> } else {
JK> return -1;
JK> }
JK> } else {
JK> return 0;
JK> }
JK> }
I don't like the implicit test against 0. Why? If it were templated, you'd
actually get a conversion to bool rather than a comparison against 0 (i.e.,
conversion to void* or, failing that, to int). Testing explicitly removes
this confusion.
template int sign(const T& num)
{
// By creating a temporary, we may avoid an extra constructor call.
// At worst, no extra work is done. In an optimizing compiler, when
// instantiated with built-in types, it will take no run-time memory,
// either.
const T zero(0);
if (zero == num) // asm type comments
return 0; // to bug Sunir.
if (num > zero) // more asm comments.
return 1; // I wonder if Sunir reads this. :-)
return -1;
}
(Bob: if you are actually considering taking that example, by all means, it's
free. However, I can't believe you'd take more work on yourself for this.
)
JK> Or a HD saver version:
JK> int foo(int num) { return num ? (num > 0 ? 1 : -1) : 0; }
That works ... again, the templatized version has to beware of implicit
compares...
template int sign(const T& num)
{
const T zero(0); // yet more asm-style
return num == zero ? 0 : (num > zero ? 1 : -1);
} // comments :-)
... Have you ever imagined a world with no hypothetical situations?
--- FastEcho 1.46
---------------
* Origin: House of Fire BBS - Toronto - (416)601-0085 - v.34 (1:250/536)
|