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

Han*_*Han 8 c++ c++17 std-variant

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.

Cru*_*ean 8

A variant may have multiple duplicates of the same type. E.g. std::variant<int, int>.

A given instance of std::variant compares equal to another if and only if they hold the same variant alternative and said alternatives' values compare equal.

因此,std::variant<int, int>具有index()0的a比较不等于std::variant<int, int>具有index()1的a,尽管有效的替代方案具有相同的类型和相同的值。

因此,该T标准未实现通用的“比较”。但是,您可以使用<variant>标头中的其他帮助器实用程序(例如std::holds_alternativestd::get<T>)来设计自己的比较运算符重载。

  • 当将 `int` 与 `std::variant&lt;int, int&gt;` 进行比较时,它可以将 _active_ 成员与该 `int` 进行比较。 (2认同)

ein*_*ica 6

这是标准委员会的任意决定。

好吧,不是随意。关键是你有一个严格比较的尺度*,其中包括以下几点:

  • 最严格:只有变体可以彼此相等,并且它们需要在替代序列(即类型)、实际替代(索引,实际上,因为你可以有多个相同类型的替代)和在价值上。
  • 不太严格:变体替代方案(作为类型和值)相等,但替代方案序列或该序列中的索引不相等(因此同一类型的两个不同替代方案中的相同值将相等) )。
  • 最宽松:活动替代方案中的值相等,如果相关,则对元素之一进行隐式转换。

这些都是有效的选择。C++ 委员会根据各种外部标准做出了决定。尝试查找该std::variant提案,因为它可能说明了这些标准是什么。

(*) - 实际上是一个格子。


Ted*_*gmo 5

我无法回答问题的原因部分,但既然您认为能够将 astd::variant<T1, T2>与 a T1or进行比较会很有用T2,也许这会有所帮助:

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

    return c && *c == t; // true if v contains a T that compares equal to t
}

template<typename T, class... Types>
inline bool operator==(const std::variant<Types...>& v, const T& t) {
    return t == v;
}
Run Code Online (Sandbox Code Playgroud)