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?
>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);
}