Skip to content
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

Proposal: meta_any::try_cast to one of a closed set of types #1172

Open
globberwops opened this issue Sep 2, 2024 · 2 comments
Open

Proposal: meta_any::try_cast to one of a closed set of types #1172

globberwops opened this issue Sep 2, 2024 · 2 comments
Assignees
Labels
enhancement accepted requests, sooner or later I'll do it

Comments

@globberwops
Copy link
Contributor

Suppose I have an instance of meta_any that I know may hold one of a closed set of different types.

With the current interface of meta_any, I can try_cast to each of the types, one after the other, and check the returned pointer until I find the correct type.

If there was e.g. an overload for try_cast that took a parameter pack of those types and returned an std::variant, containing the result of the first succesful cast, I could then std::visit that std::variant:

template <typename Arg, typename Out>
auto try_cast_impl(const entt::meta_any &any, Out &out) -> bool {
  if (const Arg *value = any.try_cast<Arg>(); value != nullptr) {
    out = *value;
    return true;
  }
  return false;
}

template <typename... Args>
auto try_cast(const entt::meta_any &any) -> std::variant<Args...> {
  std::variant<Args...> result;
  (try_cast_impl<Args>(any, result) || ...);
  return result;
}

...

const auto any_variant = try_cast<double, std::string>(any);

std::visit(
  [](auto &&arg) {
  if constexpr (std::is_same_v<T, double>) {
    ...
  } else if constexpr (std::is_same_v<T, std::string>) {
    ...
  }
}, any_variant);

This overload could be added to meta_any, but some thought would need to be put into communicating an unsuccesful try.

@skypjack skypjack self-assigned this Sep 3, 2024
@skypjack skypjack added the triage pending issue, PR or whatever label Sep 3, 2024
@skypjack
Copy link
Owner

skypjack commented Sep 3, 2024

Not sure this is easy-ish to implement actually, at least without complicating things.
Let's leave the issue open for a few days to give me time to check and give you a more precise answer. 👍

@globberwops
Copy link
Contributor Author

globberwops commented Sep 3, 2024

@skypjack Thanks for taking a look! Here's a working example: https://godbolt.org/z/dv34Gbjh6

@skypjack skypjack added enhancement accepted requests, sooner or later I'll do it and removed triage pending issue, PR or whatever labels Sep 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement accepted requests, sooner or later I'll do it
Projects
None yet
Development

No branches or pull requests

2 participants