6

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?

Hans
  • 1,741
  • 3
  • 25
  • 38

1 Answers1

5

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.

Luc Touraille
  • 79,925
  • 15
  • 92
  • 137
  • Thanks for your answer! Is this code only available in the boost sandbox? What's the easiest way to use it? Do I need to download and compile boost manually after exchanging the files in the [sandbox](https://svn.boost.org/svn/boost/sandbox/python_indexing_v2/)? – Hans May 21 '12 at 12:36
  • Apparently, this feature is not included in the release version of Boost.Python yet, so if you want to use it, you'll have to download the latest version from the sandbox and rebuild it. However, I don't know what is the status of this version (it is not reviewed yet), so your best bet is probably to stick with the dummy implementation of the comparison operators. – Luc Touraille May 21 '12 at 13:00