PyBind11 多种类型的模板类

问题描述 投票:0回答:1

我想使用 PyBind11 来包装一个专门的数组类。然而,该数组有多种形式(每种普通旧数据类型都有一个)。代码如下所示:

py::class_<Array2D<float>>(m, "Array2Dfloat", py::buffer_protocol(), py::dynamic_attr())
    .def(py::init<>())
    .def(py::init<Array2D<float>::xy_t,Array2D<float>::xy_t,float>())
    .def("size",      &Array2D<float>::size)
    .def("width",     &Array2D<float>::width)
    .def("height",    &Array2D<float>::height)
    //...
    //...

我想到的告诉 PyBind11 这些类的唯一方法是通过使用一个非常大的宏为每个 POD 复制上述内容。

有更好的方法吗?

class c++11 templates macros pybind11
1个回答
41
投票

您可以避免使用宏,而是使用模板化声明函数:

template<typename T>
void declare_array(py::module &m, const 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);
}

然后多次调用:

declare_array<float>(m, "float");
declare_array<int>(m, "int");
...
© www.soinside.com 2019 - 2024. All rights reserved.