Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't std::variant allowed to equal compare with one of its alternative types?

For example, it should be very helpful to equal compare a std::variant<T1, T2> with a T1 or T2. So far we can only compare with the same variant type.

like image 355
Maddie Avatar asked Mar 20 '19 18:03

Maddie


1 Answers

I can't answer the why part of the question but since you think it would be useful to be able to compare a std::variant<T1, T2> with a T1 or T2, perhaps this can help:

template<typename T, class... Types>
inline bool operator==(const T& t, const std::variant<Types...>& v) {
    const T* c = std::get_if<T>(&v);
    if(c)
        return *c == t;
    else
        return false;
}

template<typename T, class... Types>
inline bool operator==(const std::variant<Types...>& v, const T& t) {
    return t == v;
}
like image 115
Ted Lyngmo Avatar answered Oct 03 '22 04:10

Ted Lyngmo