Can I use typeid() to know whether a type is enum?
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...
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.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow