Last Modification: November 01, 2004

How can I control the size (storage requirement) on an enum?
Look at the following code:
// FixedEnum.h
// By James M. Curran
template<typename SizeType, typename Enum>
class FixedEnum
{
    SizeType    fe;
public:
    FixedEnum(Enum e): fe(static_cast<SizeType>(e)) {}
    FixedEnum(): fe(static_cast<SizeType>(Enum())) {}

    operator Enum() const { return static_cast<Enum>(fe);}
    SizeType asNative() {return fe;}
};

This can be used as follows:

#include "FixedEnum.h"
#include <iostream>
using std::cout;
using std::endl;

enum count {zero, one, two, three, four, thousand=1000};
FixedEnum<char, count> counter;
// should be 1 byte & work like an enum.

int main(int argc, char* argv[])
{
    counter = two;

    cout << "Counter is " << sizeof(counter) << "byte(s) long, with a value of "
         << counter << endl;

    // counter = 5; 
    // would cause compile-time error.
    counter = thousand; // warning - works, but not with expected result
}