Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to return integer from 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'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 ?

like image 734
Andrew Avatar asked Dec 16 '22 07:12

Andrew


1 Answers

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;
}
like image 95
Yochai Timmer Avatar answered Dec 28 '22 22:12

Yochai Timmer