Explicitly defaulted comparison operators in Cython

126 Views Asked by At

I want to wrap a C++ struct which has a comparison operator using Cython:

struct myStruct {
  float a;
  float b;
  float c;
  float d;
  bool operator==(const myStruct &myStr) const = default;
};

I am struggling to figure out how to perform the operator overload in Cython.

cdef struct myStruct:
    np.float32_t a;
    np.float32_t b;
    np.float32_t c;
    np.float32_t d;
   # Operator overload???

I did not specify the operator overload in the cython definition of the struct, and the build succeeded. I thought it would fail with an error.

1

There are 1 best solutions below

2
On

Cython only cares that the comparison exists. It doesn't care how the comparison is generated. Therefore just don't tell it about the = default

bool operator==(const myStruct &myStr) const

I did not specify the operator overload in the cython definition of the struct, and the build succeeded

The only consequence of not telling Cython is that you won't be able to use the operator in Cython.


You're missing two things. First operators can only be attached to cppclass and not struct so change:

cdef struct myStruct:

to

cdef cppclass myStruct:

It really doesn't matter from Cython's point of view whether it's actually defined with class or struct - this only affects the default accessibility within C++.

Second, Cython doesn't know about bool by default. Either change bool to bint (binary-int) or add from libcpp cimport bool