我在 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
引用: 6.18 Templates (在 SWIG 2.0 Documentation 中搜索“成员(member)模板”) .
关于c++ - 如何用swig实例化模板类的模板方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16218929/