1

Can I use the typeid / type_info somehow to detect whether some type is an enum (any enumerator) ?

the following works fine to detect whether a variable has type int

template<typename T>
bool is_int( T var )
{
  return strcmp( typeid(T).name(), typeid(int).name() ) == 0; 
}

but I can't use a similar version for enums - the string returned by name() differs between Linux and Windows

template<typename T>
bool is_enum( T var )
{
  // can I use typeid here?
  // eg. string_contains( typeid(var).name(), "enum" ); 
}

I've seen the templated version in Boost, but we can't use this library yet...

5
  • 6
    What problem are you really trying to solve? Commented May 31, 2012 at 12:30
  • 2
    You shouldn't use strcmp on the name()s; std::type_info supports comparison operators. Besides, the name of any type might differ from one platform to the next. Commented May 31, 2012 at 12:38
  • 2
    @larsmans: and the names are not guaranteed to be unique. Commented May 31, 2012 at 13:03
  • @MarkB: I need to create an is_enum(T) using simple tools. No Boost, no C++11. Perhaps something of the sort if( !is_int(T) && !is_pointer(T) && sizeof(T)==sizeof(some_dummy_enumerator) ) return true; - sorry about the syntax; I hope you understand what I'm trying to achieve Commented May 31, 2012 at 13:19
  • what prevents you from using boost libraries? In our company we also have very strict rules for using open source libraries / tools. But our "lawyers" approved it finally. Commented Jun 1, 2012 at 3:58

2 Answers 2

3

There are two issues with your approach:

  • you assume than names are unique. They are not (at least, the Standard does not guarantee that they are).
  • you assume that because you can detect one type, you can detect a family with the same mechanism.

If you want to know the static type of a variable, a compile-time mechanism is probably best. There are specific C++11 traits for this: std::is_enum<T> has a value static member which will be true or false depending on whether T is an enum or not.

Sign up to request clarification or add additional context in comments.

Comments

3

In the latest C++ standard, C++11, there is already functionality for checking (at compile-time) if a type is an enum or an int.

2 Comments

The question asks whether typeid can be used for that. I'm guessing not, but the answer should say so explicitly since that was the question asked.
so, guys, really, my only hope (since I have non-C++11 compilers) is the boost version of is_enum(), right ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.