Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare boost::variant in order to make it a key of std::map?

How to compare boost::variant in order to make it a key of std::map ? Seems that operator<() is not defined for boost::variant

like image 674
user222202 Avatar asked Dec 13 '25 21:12

user222202


2 Answers

EDITED TO FIX ERROR APPLYING BOOST::APPLY_VISITOR

You can create a binary visitor for your variant, 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'll probably need to overload operator() for each possible pair of types, as apposed to using the templated operator(const T &, const U &). Then you'd need to declare your map like this:

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;

Edit: for what it's worth, operator<() is defined for boost::variant however it's defined as:

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

which I'm assuming is not what you want.

like image 136
Niki Yoshiuchi Avatar answered Dec 16 '25 13:12

Niki Yoshiuchi


Perhaps you can pass a comparator to the map. Please see http://www.sgi.com/tech/stl/Map.html for an example on how to write a comparator.

like image 31
kvs Avatar answered Dec 16 '25 15:12

kvs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!