Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
This can be achieved using SFINAE, making the default overload invalid for non-numeric types: template <class T, class... Types> constexpr bool in_variant(const std::variant<Types...>...
Answer
#2: Post edited
- This can be achieved using SFINAE, making the default overload invalid for non-numeric types:
- ```
- template <class T, class... Types>
- constexpr bool in_variant(const std::variant<Types...> &) {
- const std::array hit{std::is_same_v<T, Types>...};
- return std::any_of(std::begin(hit), std::end(hit),
- [](auto v) { return v; });
- }
- void test(Value something) {
- std::visit(
- overloaded{
- [](auto a,
std::enable_if_t<in_variant<decltype(a)>(Numeric{}), int> = 0) {- std::cout << "Number" << std::endl; },
- [](auto a,
std::enable_if_t<!in_variant<decltype(a)>(Numeric{}), int> = 0) {- std::cout << "Other" << std::endl;
- },
- },
- something);
- }
- ```
- [See it live](https://coliru.stacked-crooked.com/a/c3dd91d37285211b)
- This can be achieved using SFINAE, making the default overload invalid for non-numeric types:
- ```
- template <class T, class... Types>
- constexpr bool in_variant(const std::variant<Types...> &) {
- const std::array hit{std::is_same_v<T, Types>...};
- return std::any_of(std::begin(hit), std::end(hit),
- [](auto v) { return v; });
- }
- void test(Value something) {
- std::visit(
- overloaded{
- [](auto a,
- std::enable_if_t<in_variant<decltype(a)>(Numeric{}),
- int> = 0) {
- std::cout << "Number" << std::endl; },
- [](auto a,
- std::enable_if_t<!in_variant<decltype(a)>(Numeric{}),
- int> = 0) {
- std::cout << "Other" << std::endl;
- },
- },
- something);
- }
- ```
- [See it live](https://coliru.stacked-crooked.com/a/c3dd91d37285211b)
#1: Initial revision
This can be achieved using SFINAE, making the default overload invalid for non-numeric types: ``` template <class T, class... Types> constexpr bool in_variant(const std::variant<Types...> &) { const std::array hit{std::is_same_v<T, Types>...}; return std::any_of(std::begin(hit), std::end(hit), [](auto v) { return v; }); } void test(Value something) { std::visit( overloaded{ [](auto a, std::enable_if_t<in_variant<decltype(a)>(Numeric{}), int> = 0) { std::cout << "Number" << std::endl; }, [](auto a, std::enable_if_t<!in_variant<decltype(a)>(Numeric{}), int> = 0) { std::cout << "Other" << std::endl; }, }, something); } ``` [See it live](https://coliru.stacked-crooked.com/a/c3dd91d37285211b)