Domanda

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...

È stato utile?

Soluzione

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.

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top