help with integral type conversion trait

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 ... Regards, Slawomir

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

Howard Hinnant wrote:
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
Hey, thanks! I thought I was reinventing the wheel when I came up with a similar implementation. Maybe I was just being naive, but I hoped that the Boost Numeric Conversion Library would be of some help here, no?
If you're paranoid about non-integral types you could dress up the primary template a little to return T only for integral types,
Indeed, I'm doing it with the combination of enable_if and is_integral.
-Howard
Thanks a lot! Slawomir
participants (2)
-
Howard Hinnant
-
Slawomir Lisznianski