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

Richard Smith richard at metafoo.co.uk
Mon Oct 21 11:29:04 PDT 2013


On Mon, Oct 21, 2013 at 11:28 AM, Richard Smith <richard at metafoo.co.uk>wrote:

> On Mon, Oct 21, 2013 at 6:34 AM, Stephen Kelly <steveire at gmail.com> wrote:
>
>>
>> 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;
>>  }
>>
>
> enum E1 : long {};
> static_assert(std::is_same<std::underlying_type<E1>::type, long>::value,
> ""); // ok
> static_assert(std::is_same<UnderLyingType<E1>::Type, long>::value, ""); //
> fails
>
> enum E2 : char {};
> static_assert(std::is_same<std::underlying_type<E2>::type, char>::value,
> ""); // ok
> static_assert(std::is_same<UnderLyingType<E2>::Type, char>::value, ""); //
> fails
>

*fixed*


>
>
>> Thanks,
>>
>> Steve.
>>
>>
>> _______________________________________________
>> cfe-dev mailing list
>> cfe-dev at cs.uiuc.edu
>> http://lists.cs.uiuc.edu/mailman/listinfo/cfe-dev
>>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20131021/4754e3d4/attachment.html>


More information about the cfe-dev mailing list