Skip to content

How to combine with magic_enum to generate enum reflection automatically #359

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
weypro opened this issue Jul 22, 2023 · 1 comment
Open

Comments

@weypro
Copy link

weypro commented Jul 22, 2023

No description provided.

@noodlecollie
Copy link

noodlecollie commented Apr 30, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants