Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}

edit: I'v tried to write a wrapper like Benjamin Buch suggested (thanks). I'm using template because I want it to be reusable. I managed to handle a default value but I'm struggling to make it act like a real scoped enum (last line of main doesn't compile).

#include <concepts>

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

template<typename T>
concept ScopedEnum = std::is_enum_v<T> && !std::is_convertible_v<T, int>;

template<typename Enum, auto DefaultValue>
  requires ScopedEnum<Enum>
class EnumWrapper{
public:
  EnumWrapper(): value_(DefaultValue) {}
  EnumWrapper& operator=(Enum e) { value_ = e; return *this; }
  operator Enum() const { return value_; }
private:
  Enum value_;
};

using MyEnum = EnumWrapper<EMyEnum, EMyEnum::No>;

int main() {
  MyEnum a{};
  MyEnum b = MyEnum::Yes; // how can I make this works ?
}

Can I do something like this in a template https://en.cppreference.com/w/cpp/language/enum#Using-enum-declaration ?

like image 553
Marcus Avatar asked Oct 24 '25 16:10

Marcus


1 Answers

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 define a default constructor to do whatever you want.

like image 159
user17732522 Avatar answered Oct 27 '25 05:10

user17732522