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

标签 c++ boost stdmap boost-variant

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

最佳答案

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

您可以为您的变体创建一个二进制访问者,然后使用 boost::apply_visitor 为您的 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
    }

};

您可能需要重载 operator()对于每对可能的类型,与使用模板化 operator(const T &, const U &) 相比.然后你需要像这样声明你的 map :

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;

编辑:就其值(value)而言,operator<()boost::variant 定义然而它被定义为:

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

我假设这不是您想要的。

关于c++ - 如何比较 boost::variant 以使其成为 std::map 的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4350574/

相关文章:

C++:复制到解除引用的指针

c++ - c++ 和 vb.net 应用程序之间的进程间通信

c++ - C++ 中的 OOD : Having a class with just one method?

c++ - 比较 unique_ptr 的映射

c++ - 如何找到将元素插入到 std::map 中的位置而不实际插入它

c++ - 用 set 存储 (x, y) 坐标

c++ - 为什么 boost 的 managed_mapped_file::shrink_to_fit 在 Windows 和 Linux 上表现不同?

c++ - 使用 boost asio 捕捉 Ctrl-C

C++ 编译时字符串操作

C++ 在 unique_ptr 的映射上迭代 std::accumulate():没有已知的转换