Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do I need comparison operators in boost python vector indexing suite?

I would like to expose C++ code with a

std::vector<A>

to python. My

class A{};

does not have a comparison operator implemented. When I try

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> >());
}

I get an error about comparison operators. If I change the definition of A to

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

It works like a charm.

Why do I need to implement these comparison operators? Is there any way to use the vector_indexing_suite without them?

like image 631
Hans Avatar asked May 21 '12 06:05

Hans


1 Answers

vector_indexing_suite implements a __contains__ member function, which requires the presence of an equality operator. As a consequence, your type must provide such an operator.

The sandbox version of Boost.Python solve this issue by using traits to determine what kind of operations are available on containers. For instance, find will only be provided if the values are equality comparable.

By default, Boost.Python consider all values to be equality comparable and less-than comparable. Since your type does not meet these requirements, you need to specialize the traits to specify what operations it supports:

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

This is documented here.

like image 60
Luc Touraille Avatar answered Sep 28 '22 18:09

Luc Touraille