簡體   English   中英

如何比較boost :: variant以使其成為std :: map的關鍵?

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

如何比較boost :: variant以使其成為std :: map的關鍵? 似乎沒有為boost :: variant定義operator <()

編輯修復錯誤應用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 &, 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;

編輯:對於它的值, operator<()是為boost::variant定義的,但它被定義為:

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

我假設不是你想要的。

也許你可以將比較器傳遞給地圖。 有關如何編寫比較器的示例,請參見http://www.sgi.com/tech/stl/Map.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM