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
Depending on compiler you are using you can tweak warnings to file an error if there is mismatch between emum
and target integer type.
/W4
covers this scenario - it enables C4244.-Wconversion
(standard set -Wall
-Wextra
-pedantic
is not enogh)-Wenum-int-mismatch
), but they are working only for C and Objective-C only (I do not know why). I've failed to find alternative gcc flag which would work for C++.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.