Skip to content

Instantly share code, notes, and snippets.

@etodanik
Last active July 30, 2024 10:20
Show Gist options
  • Save etodanik/05a6036a7243d491a4829597a5afef34 to your computer and use it in GitHub Desktop.
Save etodanik/05a6036a7243d491a4829597a5afef34 to your computer and use it in GitHub Desktop.
Get the current value of an std::variant at runtime in C++
// the "secret sauce" here is that everything has to happen at compile-time
// step 3) this gets called for every possible index at compile time
template <std::size_t index, class... Args> void visitor_impl(const std::variant<Args...>& variant)
{
// this code path narrows us down to the type that's currently in the variant
if (variant.index() == index)
{
// we now have the current value in a fully generic way
auto value = std::get<index>(variant);
// do what you need to do with your variant underlying value here...
}
}
// step 2) the helper uses a fold sequence to iterate over every possible type index at compile-time
template <std::size_t... IndexSequence, class... Args>
void visitor_helper(std::index_sequence<IndexSequence...>, const std::variant<Args...>& variant)
{
(visitor_impl<IndexSequence>(variant), ...);
}
// step 1) visitor creates a compile time integer sequence, and feeds it to the helper
template <class... Args> void visitor(const std::variant<Args...>& variant)
{
visitor_helper(std::make_index_sequence<sizeof...(Args)>{}, variant);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment