【问题标题】:How to compare boost::variant in order to make it a key of std::map?如何比较 boost::variant 以使其成为 std::map 的键?
【发布时间】:2010-12-03 22:45:24
【问题描述】:

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

【问题讨论】:

    标签: c++ boost stdmap boost-variant


    【解决方案1】:

    已编辑以修复错误 APPLYING 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
        }
    
    };
    

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

    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&lt;() 是为 boost::variant 定义的,但它被定义为:

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

    我假设这不是你想要的。

    【讨论】:

    • 哦,谢谢。 operator 定义的,而不是常规 boost::variant 我将从常规 boost::variant 复制代码
    • @user222202 - 查看我的编辑。您不能在地图的模板列表中调用 boost::apply_visitor。您将需要创建一个应用访问者的函数对象。
    【解决方案2】:

    也许您可以将比较器传递给地图。请参阅http://www.sgi.com/tech/stl/Map.html 了解如何编写比较器的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-18
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      相关资源
      最近更新 更多