Home Templating Structs to Combine Enums
Reply: 0

Templating Structs to Combine Enums

user2161
1#
user2161 Published in June 20, 2018, 12:04 am

I am currently doing a project that requires me to aggregate multiple enums to one huge enum. I could just write it, but managing one would be troublesome. I have an idea of using structs to wrap around the different enums and templating, the parameter would be an integer, for example:

template <int START>
struct first_enum
{
    enum constant
    {
        a = START, 
        b, c, d
    };

    static constexpr int end() { return d; }
}

template <int START>
struct second_enum
{
    enum constant
    {
        e = START, 
        f
    };

    static constexpr int end() { return f; }
}

template <int START>
struct third_enum
{
    enum constant
    {
        g = START, 
        h
    };

    static constexpr int end() { return h; }
}

Then I have another struct that inherits from the previous structs:

struct enum_all : public first_enum<0>,
                         second_enum<first_enum<0>::end() + 1>,
                         third_enum<second_enum<first_enum<0>::end() + 1>::end() + 1> {};

This way enum_all will have members a, b, c, ..., h with values ranging from 0...7.

However writing that down is very cumbersome and not scalable (imagine adding more structs).

I suspect you could do this using variadic templates, however I am still a beginner with template metaprogramming. Here is what I currently have for a base case and it compiles.

template <int START, template<int> typename ENUM>
struct enum_all_t : public ENUM<START>
{

};

Calling enum_all_t<0, first_enum>::a gives me the correct result. I tried adding another template specialization, but it tells me "error: redeclared with 3 template parameters".

template <int START, template <int> typename ENUM, template <int> typename... ENUMS>
struct enum_all_t : public ENUM<START>, enum_all_t<ENUM<START>::end() + 1, ENUMS> {};
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.265334 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO