[cfe-dev] Why is compiler support needed for std::underlying_type?

Stephen Kelly steveire at gmail.com
Mon Oct 21 06:34:18 PDT 2013


Hi,

the libcxx source has a comment that compiler support is needed for 
std::underlying_type.

Is there some reason that something like the following can't work? 


 #include <type_traits>

 template <int> struct int_for_size;
 template <>    struct int_for_size<1> { typedef signed char Signed; typedef 
unsigned char Unsigned; };
 template <>    struct int_for_size<2> { typedef short Signed; typedef 
unsigned short Unsigned; };
 template <>    struct int_for_size<4> { typedef int Signed; typedef 
unsigned int Unsigned; };
 template <>    struct int_for_size<8> { typedef long long Signed; typedef 
long long Unsigned; };

 template<typename T, bool>
 struct ApplySign
 {
   typedef typename int_for_size<sizeof(T)>::Signed Type;
 };
 template<typename T>
 struct ApplySign<T, false>
 {
   typedef typename int_for_size<sizeof(T)>::Unsigned Type;
 };

 template<typename T>
 struct UnderLyingType
 {
     typedef typename ApplySign<T, std::is_signed<T>::value>::Type Type;
 };

 enum Something {
   foo
 };

 int main()
 {
   UnderLyingType<Something>::Type s = 9;
   return 0;
 }


Thanks,

Steve.





More information about the cfe-dev mailing list