Way to check if type is an enum

How to check (without Boost or other nonstandard lib) if type passed to template is an enum type?
Thanks.

Upvotes: 1

Views: 1689

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137810

Looking at http://www.boost.org/doc/libs/1_44_0/boost/type_traits/is_enum.hpp,

If this evaluates to true:

::boost::type_traits::ice_or<
           ::boost::is_arithmetic<T>::value
         , ::boost::is_reference<T>::value
         , ::boost::is_function<T>::value
         , is_class_or_union<T>::value
         , is_array<T>::value
      >::value

Then this base template is selected:

// Don't evaluate convertibility to int_convertible unless the type
// is non-arithmetic. This suppresses warnings with GCC.
template <bool is_typename_arithmetic_or_reference = true>
struct is_enum_helper
{
    template <typename T> struct type
    {
        BOOST_STATIC_CONSTANT(bool, value = false);
    };
};

Otherwise check if it's convertible to int:

template <>
struct is_enum_helper<false>
{
    template <typename T> struct type
       : ::boost::is_convertible<typename boost::add_reference<T>::type,::boost::detail::int_convertible>
    {
    };
};

If you want to do it as well as Boost, you'll have to define all those other traits. <type_traits> is like that.

Upvotes: 2

Tony Delroy
Tony Delroy

Reputation: 106096

http://www.boost.org/doc/libs/1_44_0/libs/type_traits/doc/html/boost_typetraits/reference/is_enum.html

I appreciate you want total portability and not to use boost. If you find that impractical, you might still prefer to use a simple ifdef and the following: MSDN has a similar facility on the front page of google results for c++ is_enum. On recent GNU compilers, try your luck with using std::tr1::is_enum;

Even if you don't want to use boost, you could examine it for the technique used in determination. Looks complex enough to be exclusion of all other possibilities :-/.

Upvotes: 2

Related Questions