PrevUpHomeNext

Class template variant_comparator

A comparator object for a variant type which is appropriate to use with std::set or std::map.

Valid Expressions

expression

value

Types...

any LessThanComparable types, meeting variant type requirements

variant_comparator<variant<Types...>>

A less-than comparator object for variant<Types...>.

variant_comparator<variant<Types...>>{}(const variant<Types...>& a, const variant<Types...>& b)

True if a.which() < b.which(), or a.which() == b.which() and val_a < val_b where val_a represents the value contained by a, and similarly for b .

Definition

In header <strict_variant/variant_compare.hpp>.

namespace strict_variant {

template <typename T, template <typename> class ComparatorTemplate = std::less,
          typename WhichComparator_t = std::less<int>>
struct variant_comparator;
}

Notes

[Caution] Caution

A less-than comparator is said to induce an equality-comparator by the following identity:

a == b    if and only if    !(a < b) && !(b < a)

If a non-default WhichComparator is used (third template parameter), it still must induce the same equality-comparator as std::less<int>, or bad behavior will result.

Example

Note that even when <strict_variant/variant_compare.hpp> is included, variant does still not have a operator < overload for comparisons. Basically we consider that this is too error-prone. See a related discussion.

You can use strict_variant with std::set like so:

using var_t = variant<std::string, int>;
using set_t = std::set<var_t, variant_comparator<var_t>>;

An alternate method is to specialize std::less for variant types:

namespace std {
template <typename... Types>
struct less<variant<Types...>> : variant_comparator<variant<Types...>> {};
} // end namespace std

using var_t = variant<std::string, int>;
using set_t = std::set<var_t>;

This may save some typing if you often use variant in associative containers, but it is also less explicit.


PrevUpHomeNext