3

I came across this template of C++

template <typename T> int sgn(T val) {
        return (T(0) < val) - (val < T(0));
    }

And I have to admit I don't really get it. If I try to do a numeric application, let's say -1: (0<(-1))-(-1 < 0) => False - True I get a subtraction of Bool. Is that how it should work? Can someone explain the different steps the compiler will do?

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
tony497
  • 360
  • 1
  • 3
  • 15

3 Answers3

1

There are implicit conversions happening there: True=>1 and False=>0.

You need to check both conditions to see if the value could be equal to zero - that's how signum is defined. If your interested in checking only greater or lower than 0, you could get away with a single comparison.

Nevertheless, having your example with -1 and the posted template, in result you get:

return False - True; => return 0 - 1; => return -1;

Dusteh
  • 1,496
  • 16
  • 21
1

It will return-1 if negative +1 if possitive 0 if 0 lets say -1:

(T(0) < val) - (val < T(0))
0<-1 false or 0
-
-1 < 0 true or 1
0 - 1  = -1

lets say 0

(T(0) < val) - (val < T(0))
0<0 false or 0
-
0 < 0 false or 0
0 - 0  = 0

lets say 1:

(T(0) < val) - (val < T(0))
0<1 true or 1
-
1 < 0 false or 0
1 - 0  = 1
Ch1v1
  • 121
  • 1
  • 7
0

false and true would be converted to 0 and 1. So depending if one or both expressions evaluate to false, you get -1, 0, 1 results. That's a canon definition of signum function.

PS.Thats not an effective template, for better work there should be three specializations.

This question features answer that explains those: Is there a standard sign function (signum, sgn) in C/C++?

Swift - Friday Pie
  • 12,777
  • 2
  • 19
  • 42