Originally Posted by
grumpy
That assumes a C++11 implementation.
Before that, it was a bit tougher. Various techniques, such as using macros to identify the compiler and, based on that, using typedefs. For example, if an unsigned long type is known to be 32 bits .....
Back in the day I just used templates to work it out:
Code:
#include <limits>
namespace detail
{
enum
{
bits_per_byte = std::numeric_limits< unsigned char >::digits
};
template < typename Integer >
struct Traits
{
typedef Integer
type;
enum
{
bits = bits_per_byte * sizeof( type )
};
};
template < >
struct Traits< void >
{
typedef void
type;
enum
{
bits = 0
};
};
template < bool Condition, typename Then, typename Else >
struct If : Traits< Then >
{ };
template < typename Then, typename Else >
struct If < false, Then, Else > : Traits< Else >
{ };
}
namespace lower_bound
{
template < std::size_t Bits >
struct unsigned_bits : detail::Traits
<
typename detail::If
<
Bits <= detail::bits_per_byte,
unsigned char,
typename detail::If
<
Bits <= detail::bits_per_byte * sizeof( unsigned short ),
unsigned short,
typename detail::If
<
Bits <= detail::bits_per_byte * sizeof( unsigned int ),
unsigned int,
typename detail::If
<
Bits <= detail::bits_per_byte * sizeof( unsigned long ),
unsigned long,
typename detail::If
<
Bits <= detail::bits_per_byte * sizeof( unsigned long long ),
unsigned long long,
void
>::type
>::type
>::type
>::type
>::type
>
{ };
template < std::size_t Bits >
struct signed_bits : detail::Traits
<
typename detail::If
<
Bits <= detail::bits_per_byte,
signed char,
typename detail::If
<
Bits <= detail::bits_per_byte * sizeof( signed short ),
signed short,
typename detail::If
<
Bits <= detail::bits_per_byte * sizeof( signed int ),
signed int,
typename detail::If
<
Bits <= detail::bits_per_byte * sizeof( signed long ),
signed long,
typename detail::If
<
Bits <= detail::bits_per_byte * sizeof( signed long long ),
signed long long,
void
>::type
>::type
>::type
>::type
>::type
>
{ };
}
template < std::size_t Bits >
struct unsigned_bits : detail::Traits
<
typename detail::If
<
lower_bound::unsigned_bits< Bits >::bits == Bits,
typename lower_bound::unsigned_bits< Bits >::type,
void
>
::type
>
{ };
template < std::size_t Bits >
struct signed_bits : detail::Traits
<
typename detail::If
<
lower_bound::signed_bits< Bits >::bits == Bits,
typename lower_bound::signed_bits< Bits >::type,
void
>
::type
>
{ };
typedef unsigned_bits< 8 >::type
uint8;
typedef signed_bits< 8 >::type
int8;
typedef unsigned_bits< 16 >::type
uint16;
typedef signed_bits< 16 >::type
int16;
typedef unsigned_bits< 32 >::type
uint32;
typedef signed_bits< 32 >::type
int32;
typedef unsigned_bits< 64 >::type
uint64;
typedef signed_bits< 64 >::type
int64;
/*
You may need to update your processor for this one!
*/
typedef unsigned_bits< 128 >::type
uint128;
typedef signed_bits< 128 >::type
int128;