Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change default value initialization of scoped enum in C++ 20?

Is it possible to change the behavior of default value initialization of a scoped enum in C++ 20 ?

For exemple, in the following code, I’d like that a MyEnum variable to be initialized automaticatly with MyEnum::No when declared with MyEnum myValue{};

using MyEnumRootType = unsigned int;
using MyEnum = enum class EMyEnum: MyEnumRootType {
  Yes = 0x1,
  No = 0x2
};


int main() {
  const MyEnum myValue{}; // <- 0
  std::cout << static_cast<MyEnumRootType>(myValue);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That’s not possible directly for an enumeration (except if you are willing to change the value of No to 0x0). Enumerations are not class types (even if there is class in enum class), so you can’t affect their behavior like you can with member functions/constructors/destructors/etc of classes.

Instead you’ll have to make a class wrapper around it in which you can defined a default constructor to do whatever you want.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading