Search code examples
c++c++17std-variant

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.


Solution

  • It is an arbitrary decision by the standards committee.

    Ok, not quite arbitrary. The point is you have a scale* of strictness of comparison, with points such as:

    • Most-strict: Only variants can equal each other, and they need to match both in the sequence-of-alternatives (i.e. the type), the actual alternative (the index, really, since you can have multiple identical-type alternatives) and in value.
    • Less-Strict: Equality of both the variant alternative, as a type and the value, but not of the sequence-of-alternatives, nor the index within that sequence (so the same value within two distinct alternatives of the same type would be equal).
    • Most-relaxed: Equality of the value in the active alternative, with implicit conversion of one of the elements if relevant.

    These are all valid choices. the C++ committee made the decision based on all sorts of extrinsic criteria. Try looking up the std::variant proposal, as perhaps it says what these criteria are.

    (*) - A lattice actually.