Std: :Holds_Alternative Variadic Template

Std: :Holds_Alternative Variadic Template

Is it possible to wrap a std::holds_alternative to a variadic template to use it with more types?

For example:

std::variant<bool, int, double, std::string> var = 4;
bool r = std::holds_alternative<bool, double>(var); // holds either bool or double

2 Answers

Yes, it's doable with a simple fold expression.

template<typename... Alts, typename... Ts>
constexpr bool holds_any_of(std::variant<Ts...> const& v) noexcept {
    return (std::holds_alternative<Alts>(v) || ...);
}
5

No it's not possible. But you can roll your own:

template <class ...Request, class ...Types>
constexpr bool holdsAlternative(const std::variant<Types...>& v) noexcept
{
   return (std::holds_alternative<Request>(v) || ...);
}

to be invoked as you tried it with std::holds_alternative:

bool r = holdsAlternative<bool, double>(var); 
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.