Kamajii Kamajii - 1 month ago 7
C++ Question

Specialize an enum

How to specialize an

enum
in modern C++?

I found out that it is possible not only to provide specializations for methods but also for enumerations. The caveat is to use either based enums or provide a dummy enumerator with a value equal to the maximum value provided by any of the specializations. This makes sense to me as there might be other members that depend on the enumeration's underlying type size.

The example below works fine as long as the template class is declared as a
struct
. As soon as I declare it to be a
class
the enumerators provided in the specializations become inaccessible:

test.cc: In function 'int main()':
test.cc:27:20: error: 'Class<3>::Enum Item' is private within this context
int x = Class<3>::Item;


How to resolve this?

SSCCE



template<int i>
struct Class {
public:
enum Enum {
// Stretch underlying type (alternatively: use based enum)
MaxBit = 100
};

enum EnumAlternative: int {
// Like this
};
};

template<>
enum Class<2>::Enum {
Item = 12
};

template<>
enum Class<3>::Enum {
Item = 42
};


int main() {
int x = Class<3>::Item; // Line 27
}

Answer

You need the specialization of your Class to contain your Enum

template<>
class Class<2>
{
public:
    enum Enum
    {
        Item = 12
    };
};

int main() 
{
    int x = Class<2>::Item; // x with 12
}

Now that we have constexpr variable since C++11, consider using that.

Comments