0

Is there a way to get the equivalent of std::underlying_type in C++03 compilers?

I'm aware of some support in boost::type_traits, but there is no fully functional converter there.

Sam
  • 19,708
  • 4
  • 59
  • 82

1 Answers1

2

How about this solution?

template< class TpEnum >
struct UnderlyingType
{
    typedef typename conditional<
        TpEnum( -1 ) < TpEnum( 0 ),
        typename make_signed< TpEnum >::type,
        typename make_unsigned< TpEnum >::type
        >::type type;
};

You can find the building blocks for it (conditional, make_signed, make_unsigned in boost::type_traits)

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • That's a very fancy way to implement underlying_tpye in a C++11 compiler... However, I do have a C++03 compiler, without conditionals or make_signed – Sam Oct 01 '14 at 18:40
  • I was just thinking about that @sammy! `make_signed` required C++11. Sorry. Should I delete my answer? :/ – gsamaras Oct 01 '14 at 18:41
  • And what about `make_signed` @BillyONeal? :/ I can't think of a way to implement it without using C++11. – gsamaras Oct 01 '14 at 18:43
  • 1
    All your constructs are available in Boost, and I've been able to build my UnderlyingType. Thanks! – Sam Oct 01 '14 at 18:54
  • @G.Samaras: You make a primary template that typedefs `T` to `type`, and explicit specializations for `char`, `short`, `int`, etc. which typedef `unsigned char`, `unsigned short`, `unsigned int`, etc. as `type`. – Billy ONeal Oct 01 '14 at 19:04
  • I see @BillyONeal, pretty much like the last answer provided in my link. Glad you found a workaround sammy, after my answer! :) – gsamaras Oct 01 '14 at 19:17
  • `TpEnum( -1 )` invokes undefined behavior if `TpEnum`'s smallest enumerator is non-negative – Stephan Bergmann May 08 '15 at 10:03