Determine if integer type is signed

I'm working on some template functions to automate some stuff I find myself doing frequently with integer types. However the process is slightly different depending on whether or not I'm dealing with signed or unsigned numbers, so I'd like the template to be able to tell the difference and act accordingly.

Is there a way to determine this with minimal overhead? I know there's some typeinfo rtti stuff, but that seems like overkill (and I'm not really at all familiar with it). The only other thing I can think of is this:

1
2
3
4
5
6
7
8
if( static_cast<type>(-1) < 0 )
{
  // type is signed
}
else
{
  // type is unsigned
}


But that seems hackish and sloppy.

Any suggestions/ideas welcome and appreciated. Thanks!

--edited for clarity
Last edited on
you can use a template specialisation.
You can use numeric_limits<type>::is_signed

http://www.cplusplus.com/reference/std/limits/numeric_limits.html
Last edited on
numeric_limits is exactly what I wanted.

That's fantastic. Thanks!
A related question regarding C++ standard syntax (didn't feel a new thread would be appropriate).

One of the template functions I made:

1
2
3
4
5
6
7
8
9
template <typename smlT,typename bigT>
smlT clip_cast(bigT v)
{
    if(v > std::numeric_limits<smlT>::max())
        return std::numeric_limits<smlT>::max();
    if(v < std::numeric_limits<smlT>::min())
        return std::numeric_limits<smlT>::min();
    return static_cast<smlT>(v);
}


smlT will need to be explicitily supplied, however bigT can be figured by the parameter passed... so can I legally call that function with the following:

1
2
3
4
long foo = 0x1FFFF;
short bar;
bar = clip_cast<short>(foo);       // is this ok?
bar = clip_cast<short,long>(foo);  // or is this necessary? 


The former works in MSVS, but I wonder if this is legal according to C++ standards.

Thanks!
Yes.
function template arguments could be deduced from the function arguments
so that is standard C++
awesome.

Thanks.
Topic archived. No new replies allowed.