c++visual-studio-2017macros

Compile-time check that a variable is signed/unsigned


I'm trying to come up with some compile-time ways to check if a certain variable is signed or unsigned. Actually, I was using the following macro for quite some time to check for a signed variable:

#ifdef _DEBUG
#define CHECK_SIGNED(v) if((v) == -(v)){}
#else
#define CHECK_SIGNED(v)
#endif

and then the following will pass it:

INT rr = 0;
CHECK_SIGNED(rr);

while the following:

UINT rr = 0;
CHECK_SIGNED(rr);

will generate a compile-time error:

error C4146: unary minus operator applied to unsigned type, result still unsigned

So now I am trying to come up with a similar check for unsigned variable. Any suggestions?

PS. Although I'm using VS 2017 it'd be nice to make it backwards compatible with older C++ standards.


Solution

  • Could use something like this :

    static_assert(std::is_signed<decltype(rr)>::value, "Not signed number");
    

    and the sister version std::is_unsigned

    Also, those are not very difficult to implement on your own for supporting old compilers.