wip
wip

Reputation: 2442

In a class template how to detect if the template parameter is an enumeration type?

In a class template, how to detect if the template parameter is an enumeration type ?

Here is a simplified example of what I would like to do : http://ideone.com/3CafY. How would you implement IsTEnum() so that the output is correct ?

I feel there should be a boost function that solves this problem, however I am not allowed to use boost (nor the standard library std:: functions) in my current project.
Nonetheless, I would also be interested to know both methods using boost or not (even if the solution does not handle pointer or const types).

Upvotes: 3

Views: 1804

Answers (3)

Sam Ginrich
Sam Ginrich

Reputation: 841

Before C++11 there are detectors for built-in types and types convertible to int

template <typename E> struct IntTest
{
    static char eval(...)
    {
        return ' ';
    }
    static int eval(int z)
    {
        return 1;
    }

    static const bool knowsInt = sizeof(int) == sizeof(eval(*(E*)0));
};

IntTest<enum_type>::knowsInt will return true for some enum_type. When you exclude built-in types and classes with implicite conversion to int like

class R
{
public:
    int z;
    operator int()
    {
        return z;
    }
};

you can assume that you have an enumeration.

Upvotes: 1

Rontogiannis Aristofanis
Rontogiannis Aristofanis

Reputation: 9063

If you can't use C++11 then write:

#include <tr1/type_traits>
#include <iostream>
using namespace std;

int main() {
   cout << tr1::is_enum<int>::value << "\n";
   return 0;
}

The namespace tr1 includes some header files from C++11 which can be used in pre standard C++.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227390

You can use C++11's std::is_enum for that purpose. You are right in that boost has the same solution. If you cannot use boost or C++11, you can always look at the implementations for inspiration.

Upvotes: 7

Related Questions