How is a prediction for something having a signed numeric type?

Suppose I have some boilerplate code that does the following:

T x = foo();
T y = -x;

Now, if T is a non-numeric type (or that does not have a unary minus implemented), compilation will simply fail. But if it is unsigned int, unsigned short, etc., it will be successful, with a warning. Therefore I would like to be able to do

T x = foo();
if (/* magic condition */ {
    T y = -x;
}

Can I write an expression for a condition - which is checked either at compile time or at run time - of type T, which is some kind of number type? for example using typeid?

Note:

  • A statement would also be nice, but I would like something more flexible.
+4
2

++ 11 is_unsigned, static_assert:

#include <type_traits>

template <typename T>
void foo()
{
    static_assert(std::is_unsigned<T>::value);

    T x = /* ... */
    T y = -x;

    /* ... */
}

, , if:

template <typename T>
void foo()
{
    if (!std::is_unsigned<T>::value) {
        /* To arrive here and for the following
           not to error out, we must have a numeric
           type that not unsigned! */

        T x = /* ... */
        T y = -x;
    }
    else {
       /* Do something else for unsigned numeric
          types */
    }
}

, std::enable_if , , .

+6

, .

static_assert(std::is_unsigned<T>::value, "Not unsigned!");  

( type_traits .)

, enable_if, , :).

+4

All Articles