swig python 带类型推导的模板函数

swig python template functions with type deduction

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

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

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

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

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

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

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

可能吗?还是我的想法完全错误?

使用 %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)