Is it possible to return an integer from a template function?

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 works, but I'm not sure that it is useful to return a numeric value when in fact my function should return T. Is this function good?

+4
source share
5 answers

No, T may be a type that is not a integer.

In this case, it will fail during compilation.

If you want it to be intact in design, declare it like this.

 template<class T> int sign(const T &value) { if (value > 0) return 1; else if (value < 0) return -1; return 0; } 
+7
source

Your function will compile only if there is an implicit conversion from int to T If this is your intention, everything is in order, but in reality it is not very good.

I think it is better if you rewrite your code to return T , possibly using something like:

 //return T(0); return static_cast<T>(0); // Better alternative as suggested by Steve Jessop 

This explicitly builds a T from int. Keep in mind that if someone calls this method with T , which can build from int , it will work - no matter what this constructor really means.

+2
source

Is there a reason why you use T as the return type? You should consider changing it to some integral or enum{USINGNED,ZERO,SIGNED} . In this case, your function will work as long as T has overloaded operators > and < .

+2
source

As long as you can drop -1/0/1 to T , this is exactly what will happen. I believe that what you want to achieve has a sign of the same type as the input, so the only thing you can do is add an explicit cast, which will practically have no meaning, ”said Steve in the comments, it will matter depending on T explicit constructor.

+1
source

I think this is normal, because T will be the number, how do you want to know the sign. Allows you to view the function of the caller.

 double x = -5.2; int ret = sign(x); 

in the last statement, the sign will return int constant, which will be assigned to ret (implicit cast type, if required);

0
source

Source: https://habr.com/ru/post/1381272/


All Articles