rttr icon indicating copy to clipboard operation
rttr copied to clipboard

How to combine with magic_enum to generate enum reflection automatically

Open weypro opened this issue 2 years ago • 1 comments

weypro avatar Jul 22 '23 15:07 weypro

In case this is useful to anyone in future, I worked out how to do this. Helpfully, much of the magic_enum reflection is constexpr, so can be used with templates - the only tricky bit is to convert an enum entry list into a sequence of rttr::value arguments for the registration call. I've not had to go this deep on template metaprogramming before, so this code might not be very polished, but it does seem to work. You can just call RegisterMagicEnum<MyEnum>() within RTTR_REGISTRATION to register your enum.

// Given an array of magic_enum entries, registers these as an RTTR enumeration.
// This is done by also receiving an index sequence whose length matches
// the length of the array. Template parameter pack expansion is used to
// expand the number of rttr::value arguments passed to the enumeration
// registration function.
template<typename EnumType, size_t ArraySize, std::size_t... Indices>
static void RegisterMagicEnumHelper(
	std::array<std::pair<EnumType, std::string_view>, ArraySize> enumEntries,
	std::index_sequence<Indices...>
) noexcept
{
	rttr::registration::enumeration<EnumType>(magic_enum::enum_type_name<EnumType>().data())(
		rttr::value(
			rttr::string_view(std::get<Indices>(enumEntries).second.data()),
			std::get<Indices>(enumEntries).first
		)...
	);
}

template<typename EnumType>
static void RegisterMagicEnum() noexcept
{
	constexpr std::size_t NUM_ENUM_ENTRIES = magic_enum::enum_count<EnumType>();

	RegisterMagicEnumHelper<EnumType, NUM_ENUM_ENTRIES>(
		magic_enum::enum_entries<EnumType>(),
		std::make_index_sequence<NUM_ENUM_ENTRIES> {}
	);
}

noodlecollie avatar Apr 30 '25 06:04 noodlecollie