首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何用pybind11包装模板化的类

如何用pybind11包装模板化的类
EN

Stack Overflow用户
提问于 2017-07-05 19:32:42
回答 2查看 2.6K关注 0票数 7

我有一个类似于下面的类结构,其中我有两个类型A和B,它们具有相似的签名,只是参数/返回类型不同。然后,我使用一个类模板来处理这两个类,在Python中实现了一个静态的鸭子类型变体。现在,我想用pybind11将这段代码封装到Python中,我希望得到一个使用标准的动态鸭子类型来接受这两种类型的类。我该怎么做呢?

我基本上是在寻找一种方法来禁用pybind11中的严格类型检查,或者指定多个类型,以便同时接受TypeA和TypeB。按照下面示例的定义方式,只有TypeA通过检查。我也不能将A和B统一到一个基类中,因为有不同的函数签名。

代码语言:javascript
运行
复制
#include <pybind11/pybind11.h>
#include <iostream>

class TypeA {
public:
    typedef double InType;
    typedef std::string OutType;
    const OutType operator()(const InType arg)
    {
        return std::to_string(arg);
    }
};

class TypeB {
public:
    typedef std::string InType;
    typedef double OutType;
    const OutType operator()(const InType arg)
    {
        return std::stod(arg);
    }
};

template<typename T>
class DuckType {
public:
    void runType(const typename T::InType arg)
    {
        T x;
        const typename T::OutType y = x(arg);
        std::cout << y << std::endl;
    }
};

namespace py = pybind11;

PYBIND11_PLUGIN(ducktyping) {

    pybind11::module m("ducktyping", "Testing ducktyping with templates");

    typedef DuckType<TypeA> Type;
    py::class_<Type>(m, "DuckType")
    .def("run_type", &Type::runType);
    ;
    return m.ptr();
}
EN

回答 2

Stack Overflow用户

发布于 2019-06-18 20:30:43

如果要绑定的函数具有可以在C++中“驱动”推理的参数,则可以使用它们来驱动pybind11https://pybind11.readthedocs.io/en/stable/advanced/functions.html#overload-resolution-order中的重载解析

例如,您可以将您的实例化绑定为重载,然后让pybind11处理它:

代码语言:javascript
运行
复制
// Let's say `DuckType::runType` is static.
m.def("runType", &DuckType<TypeA>::runType, py::arg("arg"));
m.def("runType", &DuckType<TypeB>::runType, py::arg("arg"));

然后,假设用户可以实例化这些类型,并且InType被定义为不会意外地截获另一个类的类型,那么分派将在Python中工作:

代码语言:javascript
运行
复制
runType(arg=1.2)  # TypeA
runType(arg="hello world")  # TypeB
票数 1
EN

Stack Overflow用户

发布于 2021-05-26 15:02:24

在以下github问题中可以找到一个示例

https://github.com/pybind/pybind11/issues/199#issuecomment-323995589

为了完整,我将把示例复制到这里

代码语言:javascript
运行
复制
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

namespace py = pybind11;

template <typename T>
class MyClass : public SuperClass
{
 MyClass(int foo)   {}
 void func (int baa)
}

template <typename T>
void MyClass<T> :: func(int baa) {}

PYBIND11_MODULE(example, m) {
py::class_< MyClass<double>, shared_ptr< MyClass<double> >, SuperClass>(m, "MyClass")
 .def(py::init<int>())
 .def("func", &MyClass<double>::func);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44925081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档