本文介绍了PyBind11多种类型的模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用PyBind11包装一个专门的数组类.但是,该数组有多种形式(每种普通旧数据类型一种).代码如下:

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:

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复制以上内容.

The only way I've thought of to tell PyBind11 about these classes is by duplicating the above for each POD through the use of a very large macro.

有更好的方法吗?

推荐答案

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

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");
...

这篇关于PyBind11多种类型的模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-08 17:36