0

Can't use variant.index() in constexpr statements so need to iterate variant and return true if it can cast to some type or false if it's emtpy or contains zero value. Try this code, but seems index sequence is not variadic type and ... operator not available in this case.

template <typename T>
bool has_value(T value) noexcept {
    if constexpr (std::is_convertible_v <T, bool>) {
        return value;
    }
    else if constexpr (is_variant_v<T>) {
        constexpr size_t N = std::variant_size_v<decltype(value)>;
        using variant_sequence = typename std::make_index_sequence<0, N-1>::type;
        bool __has_value = (( std::get<variant_sequence>(value), true) || variant_sequence... ) ;
        return __has_value;
    }
    return false;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • Empty, you mean `std::monostate` or T == `std::variant<>` (which is ill formed)? [`std::visit`](https://en.cppreference.com/w/cpp/utility/variant/visit) is `constexpr` BTW. – Jarod42 Apr 08 '21 at 16:16
  • I have some variadic variant, which is user setting, for example variant. I have this Targs... separatly but don't want to use them everytime I work with variant type. So I want to parse this variant without Ts... giving this sequence from variant type itself immediately. Seems with combination of variant_length and index sequence it is possible. – Sergey Inozemcev Apr 08 '21 at 16:34
  • I also have some variable which is same variant type, and I initialise this variable zero value in declaration, maybe I can simply check initial value with literal 0 in std::get method but I am not sure that it is correct way to check complex variant value. – Sergey Inozemcev Apr 08 '21 at 16:34

1 Answers1

2

I think you want:

template <typename T>
bool has_value(T value) noexcept {
    if constexpr (std::is_convertible_v <T, bool>) {
        return value;
    } else if constexpr (is_variant_v<T>) {
        return std::visit([](const auto& elem){ return has_value(elem); }, value);
    }
    return false;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302