如何使用swig实例化模板类的模板方法

How to instantiate a template method of a template class with swig?

本文关键字:模板方法 何使用 swig 实例化      更新时间:2023-10-16

我在c++中有一个模板类,这个类的一个方法被模板化为另一个占位符

template <class T>
class Whatever {
public:
    template <class V>
    void foo(std::vector<V> values);
}

当我将这个类传输到swig文件时,我做了

%template(Whatever_MyT) Whatever<MyT>;

不幸的是,当我试图在python的Whatever_MyT实例上调用foo时,我得到了一个属性错误。我认为我必须用

实例化成员函数
%template(foo_double) Whatever<MyT>::foo<double>;

这是我在c++中写的,但它不起作用(我得到一个语法错误)

问题在哪里?

先声明成员模板的实例,再声明类模板的实例。

例子
%module x
%inline %{
#include<iostream>
template<class T> class Whatever
{
    T m;
public:
    Whatever(T a) : m(a) {}
    template<class V> void foo(V a) { std::cout << m << " " << a << std::endl; }
};
%}
// member templates
// NOTE: You *can* use the same name for member templates,
//       which is useful if you have a lot of types to support.
%template(fooi) Whatever::foo<int>;
%template(food) Whatever::foo<double>;
// class templates.  Each will contain fooi and food members.
// NOTE: You *can't* use the same template name for the classes.
%template(Whateveri) Whatever<int>;
%template(Whateverd) Whatever<double>;

输出
>>> import x
>>> wi=x.Whateveri(5)
>>> wd=x.Whateverd(2.5)
>>> wi.fooi(7)
5 7
>>> wd.fooi(7)
2.5 7
>>> wi.food(2.5)
5 2.5
>>> wd.food(2.5)
2.5 2.5

Reference: 6.18 Templates (search "member template") in the SWIG 2.0 Documentation.