Last active
July 30, 2024 10:20
-
-
Save etodanik/05a6036a7243d491a4829597a5afef34 to your computer and use it in GitHub Desktop.
Get the current value of an std::variant at runtime in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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