首页 > 解决方案 > 带有类型推导的 swig python 模板函数

问题描述

我想将以下 C++ 代码包装到 python 模块中。

class minimal
{
public:
    minimal()
    {
    }
    ~minimal()
    {
    }

    template<class T>
    void foo(T a)
    {
        auto z = a; 
    }
};

如您所见,我有模板函数,并且我知道我不能在 Python 中调用模板函数,但是我希望由于类型推导,使用 int 或字符串参数调用 foo 会成功。.cxx 文件中仍然没有 foo,但是 SWIG 文档说,它支持类型推导

所以我的目标是像这样编写python代码:

#C++ analog: minimal.foo(123)
minimal().foo(123) 

#C++: to minimal().foo(0.1)
minimal().foo(0.1) 

是否可以?还是我的想法完全错误?

标签: pythonc++swig

解决方案


使用该%template指令指示 SWIG 创建特定模板的实现。只有声明的模板实例可用。

例子:

%module test

%inline %{

class minimal
{
public:
    minimal()
    {
    }
    ~minimal()
    {
    }

    template<class T>
    void foo(T a)
    {
        auto z = a; 
    }
};

%}

%template(foo) minimal::foo<int>;
%template(foo) minimal::foo<double>;

例子:

>>> import test
>>> m=test.minimal()
>>> m.foo(1)
>>> m.foo(1.5)
>>> m.foo('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\test.py", line 115, in foo
    return _test.minimal_foo(self, *args)
NotImplementedError: Wrong number or type of arguments for overloaded function 'minimal_foo'.
  Possible C/C++ prototypes are:
    minimal::foo< int >(int)
    minimal::foo< double >(double)

推荐阅读