如何比较boost :: variant以使其成为std :: map的关键?

use*_*202 3 c++ boost stdmap boost-variant

如何比较boost :: variant以使其成为std :: map的关键?似乎没有为boost :: variant定义operator <()

Nik*_*chi 5

编辑修复错误应用BOOST :: APPLY_VISITOR

您可以为变体创建二进制访问者,然后使用boost :: apply_visitor为您的地图创建比较器:

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
    }

};
Run Code Online (Sandbox Code Playgroud)

您可能需要operator()为每个可能的类型对重载,因为使用模板化operator(const T &, const U &).然后你需要像这样声明你的地图:

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;
Run Code Online (Sandbox Code Playgroud)

编辑:对于它的价值,operator<()定义为boost::variant它定义为:

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

我假设不是你想要的.