c++ - 为什么在 boost python vector 索引套件中需要比较运算符?

标签 c++ boost boost-python comparison-operators

我想用

公开 C++ 代码
std::vector<A>

到 python 。我的

class A{};

没有实现比较运算符。当我尝试

BOOST_PYTHON_MODULE(libmyvec)
{
  using namespace boost::python;
  class_<A>("A");
  class_<std::vector<A> >("Avec")
    .def(boost::python::vector_indexing_suite<std::vector<A> >());
}

我收到有关比较运算符的错误。如果我将 A 的定义更改为

class A {
public:
  bool operator==(const A& other) {return false;}
  bool operator!=(const A& other) {return true;}
};

它就像一个魅力。

为什么我需要实现这些比较运算符?有没有办法在没有它们的情况下使用 vector_indexing_suite

最佳答案

vector_indexing_suite 实现了一个 __contains__ 成员函数,它需要一个相等运算符。因此,您的类型必须提供这样的运算符。

Boost.Python 的沙盒版本通过使用特征来确定容器上可用的操作类型来解决这个问题。例如,find 仅在值相等且可比较时才会提供。

默认情况下,Boost.Python 将所有值视为相等可比较和小于可比较。由于您的类型不满足这些要求,您需要专门化特征以指定它支持哪些操作:

namespace indexing {
  template<>
  struct value_traits<A> : public value_traits<int>
  {
    static bool const equality_comparable = false;
    static bool const lessthan_comparable = false;
  };
}

这已记录在案 here .

关于c++ - 为什么在 boost python vector 索引套件中需要比较运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10680691/

相关文章:

c++ - boost::变体和多态性

c++ - Boost python 和虚拟类

c++ - 保存复杂的脚本对象的状态

c++ - 将非静态成员函数作为回调传递

c++ - ODR 的目的是什么?

c++ - Boost 多列索引的多索引复合键

c++ - Boost 包含了严重破坏——但这不是 Boost 的错

c++ - 如何在 Boost::Python 中向 C++ 类型添加自定义隐式转换?

c++ - 如何跟踪计划稍后删除的对象?

c++ - 如何在 C++ 中从另一个协程调用一个协程?