PyBind11 Template Class of Many Types

前端 未结 1 1595
旧时难觅i
旧时难觅i 2020-12-15 23:56

I\'d like to use PyBind11 to wrap a specialized array class. However, the array is available in many flavours (one per each plain-old-datatype). The code looks like this:

相关标签:
1条回答
  • 2020-12-16 01:00

    You can avoid using macros and instead go with a templated declaration function:

    template<typename T>
    void declare_array(py::module &m, std::string &typestr) {
        using Class = Array2D<T>;
        std::string pyclass_name = std::string("Array2D") + typestr;
        py::class_<Class>(m, pyclass_name.c_str(), py::buffer_protocol(), py::dynamic_attr())
        .def(py::init<>())
        .def(py::init<Class::xy_t, Class::xy_t, T>())
        .def("size",      &Class::size)
        .def("width",     &Class::width)
        .def("height",    &Class::height);
    }
    

    And then call it multiple times:

    declare_array<float>(m, "float");
    declare_array<int>(m, "int");
    ...
    
    0 讨论(0)
提交回复
热议问题