2

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
4
  • overflow is well defined for unsigned types. You could use an enum class, and then write and constrain the operations from there. Commented Aug 7 at 16:22
  • 11
    A enum class wouldn't allow implicit conversions at all. If you need more control than this, make a class. Commented Aug 7 at 16:28
  • 3
    I don't know why it's not warning (directly assigning an uint16_t to an `` uint8_t` gives the expected warning about a possible value change); however, if you were to switch to enum class -- which is recommended anyway for type-safety -- you wouldn't even be able to assign to other types without a cast. Commented Aug 7 at 16:32
  • 4
    This is what brace initialization is for use : std::uint8_t copyfail{test}; Commented Aug 7 at 17:06

1 Answer 1

5

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

  • MSVC simple /W4 covers this scenario - it enables C4244.
  • clang requires adding -Wconversion (standard set -Wall -Wextra -pedantic is not enogh)
  • gcc has some flags (for example -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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have taken this approach to use brace initialization, I also found std::underlying_type to be useful in some circumstances stackoverflow.com/a/14589519/10633627 for others who might be interested, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.