I want to write a sign function template. I did it like this:
template<class T> T sign(const T &value)
{
if (value > 0) return 1;
else if (value < 0) return -1;
return 0;
}
It's working, but i'm not sure if it is good to return a numerical value when actually my function should return T. Is this function good ?
No, T
might be a type that doesn't have a cast from integer.
In that case it will fail at compile time.
If you want it to be an integer by design, declare it so.
template<class T> int sign(const T &value)
{
if (value > 0) return 1;
else if (value < 0) return -1;
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With