开发者

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜