Skip to content

Allow custom getter/setter for enum classes? #693

@AmaiKinono

Description

@AmaiKinono

I tried to bind the value of a select element to an enum class. To do this, I defined custom getters and setters:

enum class BookType {
  one_way,
  return_flight,
};

// ctor is an Rml::DataModelConstructor
ctor.RegisterScalar<BookType>([](const BookType& booktype, Rml::Variant& variant) {
  if (booktype == BookType::one_way) {
    variant = "one_way";
  } else if (booktype == BookType::return_flight) {
    variant = "return";
  } else {
    Rml::Log::Message(Rml::Log::LT_WARNING, "Invalid booktype.");
  }
 },
  [](BookType& booktype, const Rml::Variant& variant) {
    Rml::String str = variant.Get<Rml::String>();
    if (str == "one_way") {
      booktype = BookType::one_way;
    } else if (str == "return") {
      booktype = BookType::return_flight;
    } else {
      Rml::Log::Message(Rml::Log::LT_WARNING, "Invalid value :'%s'.", str.c_str());
    }
  });

I got this compile error:

<path-to-RmlUi>/Include/RmlUi/Core/DataModelHandle.h:146:51: error: static assertion failed: Cannot register scalar data type function. Arithmetic types and String are handled internally and does not need to be registered.
  146 |         static_assert(!is_builtin_data_scalar<T>::value,
      |

So because BookType is an enum class, it's counted as builtin scalar type.

I do think it's good to offer default binding to plain enum type, but enum classes are scoped, so it's possible that people want custom getters/setters on them; And because enum classes don't convert implicitly to integers, I think it's less reasonable to convert enum class to integers internally.

I do have a local fix of is_builtin_data_scalar that changes the is_enum in it to something like is_plain_enum. But that seems like a breaking change, so I'm not sure if this is the right thing to do.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions