Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 577
wip Avatar asked Nov 22 '25 13:11

wip


2 Answers

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.

like image 186
juanchopanza Avatar answered Nov 25 '25 02:11

juanchopanza


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.

like image 31
Sam Ginrich Avatar answered Nov 25 '25 02:11

Sam Ginrich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!