c++c++17std

C++ Enum storage size conversion prevention


Is is possible to prevent explicit enum storage size conversions? I tried overloading = but this does not seem to work on primitive types.

enum GlobalSettingTableType : std::uint16_t
{
   first = 0,
   second = 1,
   other = 1000 // out of range for uint8_t
};


GlobalSettingTableType test = GlobalSettingTableType::other;
std::uint16_t copyOK = test;
std::uint8_t copyfail = test; // Should not compile

Solution

  • Depending on compiler you are using you can tweak warnings to file an error if there is mismatch between emum and target integer type.

    Here is godbolt demo

    In case you are writing a new code, using braces as coding convention is a good solution for all compilers - as Pepijn Kramer proposed in comment.
    Tweaking warnings should be good for already existing code.