Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I somehow elegantly forbid using unsingned variables in my template function?

Consider this piece of code:

template <typename T>
T abs(const T& n)
{
    if (!std::is_signed<T>::value)
        throw logic_error;
    if (n < 0)
        return -n;
    return n;
}

What do I want to do: I want to completely forbid the usage of my function with unsigned variables since it doesn’t make sense and probably user is don’t even know that he uses anunsigned variable. For example, I can somewhat avoid this problem:

template <typename T>
T abs(const T& n)
{
    if constexpr(!std::is_signed<T>::value)
        n += "";
    if (n < 0)
        return -n;
    return n;
} 

But if I call abs(4u) the compiler errors are not much obvious. Something like can’t apply += const char[1] to double. Can I make it somehow more obvious? Or just make multiple overloadings?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

#include <type_traits>

template <typename T>
T abs(T n)
{
  static_assert(std::is_signed<T>::value, "Type must be unsigned.");
  if (n < 0) { return -n; }
  return n;
}

int main()
{
    return abs(3u);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading