小编Joh*_*han的帖子

如何用pybind11包装模板化的类

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

我基本上是在寻找一种方法来禁用pybind11中的严格类型检查或指定多种类型,以便接受TypeA和TypeB.定义下面示例的方式,只有TypeA通过检查.由于功能签名不同,我也无法将A和B统一到基类中.

#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 …
Run Code Online (Sandbox Code Playgroud)

c++ python templates pybind11

6
推荐指数
1
解决办法
826
查看次数

标签 统计

c++ ×1

pybind11 ×1

python ×1

templates ×1