How to compare boost :: variant to make it the std :: map key?

How to compare boost :: variant to make it the std :: map key? It seems that the <() operator is not defined for boost :: variant

+3
source share
2 answers

EDIT AN ERROR STATING A BOOST: APPLY_VISITOR

You can create a binary visitor for your option, and then use boost :: apply_visitor to create a comparator for your map:

class variant_less_than
    : public boost::static_visitor<bool>
{
public:

    template <typename T, typename U>
    bool operator()( const T & lhs, const U & rhs ) const
    {
            // compare different types
    }

    template <typename T>
    bool operator()( const T & lhs, const T & rhs ) const
    {
            // compare types that are the same
    }

};

You will probably have to overload operator()for each possible pair of types, as indicated in the use of the template operator(const T &, const U &). Then you need to declare your card as follows:

class real_less_than
{
public:
  template<typename T>
  bool operator()(const T &lhs, const T &rhs)
  {
    return boost::apply_visitor(variant_less_than(), lhs, rhs);
  }
};

std::map<boost::variant<T, U, V>, ValueType, real_less_than> myMap;

: operator<() boost::variant, :

bool operator<(const variant &rhs) const
{
  if(which() == rhs.which())
    // compare contents
  else
    return which() < rhs.which();
}

, , .

+5
+1

Source: https://habr.com/ru/post/1778420/


All Articles