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.
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_alternative和std::get<T>)来设计自己的比较运算符重载。
这是标准委员会的任意决定。
好吧,不是很随意。关键是你有一个严格比较的尺度*,其中包括以下几点:
这些都是有效的选择。C++ 委员会根据各种外部标准做出了决定。尝试查找该std::variant提案,因为它可能说明了这些标准是什么。
(*) - 实际上是一个格子。
我无法回答问题的原因部分,但既然您认为能够将 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)
| 归档时间: |
|
| 查看次数: |
415 次 |
| 最近记录: |