|
Boost Users : |
From: Howard Hinnant (hinnant_at_[hidden])
Date: 2005-07-23 17:54:18
On Jul 23, 2005, at 1:48 PM, Slawomir Lisznianski wrote:
> Hello,
>
> I'm looking for a way to convert an integral type into its unsigned
> equivalent. For example, assume a trait called to_unsigned_integral
> such
> that:
>
> to_unsigned_integral<int>::type ---> yields unsigned int
> to_unsigned_integral<short>::type ---> yields unsigned short
> to_unsigned_integral<unsigned char>::type ---> yields unsigned char
> ...
template <class T> struct to_unsigned_integral
{typedef T type;};
template <> struct to_unsigned_integral<char>
{typedef unsigned char type;};
template <> struct to_unsigned_integral<signed char>
{typedef unsigned char type;};
template <> struct to_unsigned_integral<short>
{typedef unsigned short type;};
template <> struct to_unsigned_integral<int>
{typedef unsigned int type;};
template <> struct to_unsigned_integral<long>
{typedef unsigned long type;};
#if YOUVE_GOT_IT
template <> struct to_unsigned_integral<long long>
{typedef unsigned long long type;};
#endif
I've found it pretty useful myself too. :-)
If you're paranoid about non-integral types you could dress up the
primary template a little to return T only for integral types, and void
otherwise (or static_assert). But in practice I haven't come across
the need to go to that trouble.
This tool comes in very handy when doing bit manipulations on generic
types, e.g.:
template <class T>
inline
T
rotate_left(T x, int n = 1);
(bit manipulations are more portable if you traffic in unsigned types)
-Howard
Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net