I would like to overload a member of a class/structure in Python/C++ using pybind.
A minimal code example looks would be
#include <iostream>
#include <string>
#include <vector>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/complex.h>
#include <pybind11/functional.h>
#include <pybind11/chrono.h>
#include <memory>
#include <cctype>
namespace py = pybind11;
struct Example {
Example(){
some_names = {"Marc", "Felix"};
}
int someFunction(const int& param) {
return param;
}
int someOverloadedFunction(const float& param) {
return static_cast< int >(param);
}
float someOverloadedFunction(const int& param) {
return static_cast< float >(param);
}
//++++++++ Variables ++++++++
std::vector<std::string> some_names;
};
PYBIND11_MODULE(example, m) {
m.doc() = "Example to be integrated into the main elements.";
py::class_<Example>(m, "Example")
.def(py::init<>())
.def("someFunction", &Example::someFunction)
// Version 1 (Working): Use Overload Cast
// .def("someOverloadedFunction", py::overload_cast< const int& >( &Example::someOverloadedFunction)) // py::const_
// .def("someOverloadedFunction", py::overload_cast< const float&>( &Example::someOverloadedFunction)); // py::const_
// Version 2 (Not working): Use Lambda Functions;
.def("someOverloadedFunction", [](const int &a){return &Example::someOverloadedFunction(a); })
.def("someOverloadedFunction", [](const float &a){return &Example::someOverloadedFunction(a); });
}
// Run with:
// c++ -O3 -Wall -shared -std=c++14 -fPIC $(python3 -m pybind11 --includes) minimal_example.cpp -o minimal_example$(python3-config --extension-suffix)
While the overload_cast is working, it was recommended to use lambda functions. However, the Example::someOverloadedFunction
is not found in this example and I assume, the reason is, that Example was not initialized here.
Error:
minimal_example.cpp:43:96: error: cannot call member function ‘float Example::someOverloadedFunction(const int&)’ without object
43 | .def("someOverloadedFunction", [](const int &a){return &Example::someOverloadedFunction(a); })
How do I do it the correct way?