Reputation: 51
I'm using pybind11 to expose C++ functions to a Python interface. I want to wrap the overloaded assignment operator but don't know how. The documentation and examples provided don't really cover it, at least from what I saw.
Here's a simplified version of what I'm trying to do:
class Num{
public:
Num(const double& num) : m_val(num), m_type(Num::Type::e_none){}
Num& operator=(const double& rhs){m_val = rhs;}
private:
double m_val;
};
And here's the wrapping:
PYBIND11_MODULE(demo, m){
py::class_<Num>(m, "Num")
.def(py::init<const double&>())
// Overloaded assignment operator binding ?
;
}
My main concern is preserving Num's data type when assigning it to a float. e.g.:
>>> m = Num(4.5)
>>> type(m)
<class 'demo.Num'>
>>> m = 5.5
>>> type(m)
<class 'float'>
This is my first time working with C++ extensions and bindings so any insight on what I should do would be great!
Upvotes: 5
Views: 3380
Reputation: 1
I don't have enough reputation to add a comment to Voya's answer, but the syntax in plfoley's answer using "py::overload_cast" is incorrect. It should be .def("assign", py::overload_cast<const double&>(&Num::operator=));
Upvotes: 0
Reputation: 11
.def("assign", &Num::operator=);
Please refer to https://github.com/pybind/pybind11/issues/250 for more details.
Upvotes: 1