c++ - 如何用swig实例化模板类的模板方法?

标签 c++ python swig

我在 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/

相关文章:

c++ - C++ (GCC) 中的四倍精度

c++ - 如何指定 C++ 类的特定方法使用模板?

c++ - 在同一个 VBO OpenGL 上绘制具有不同纹理的不同对象

c++ - Qt QMainWindow 中央小部件删除

python - 如何解决 django 的 send_mail 无法访问网络的问题?

c - 使用 SWIG,取消引用指向 TCL 变量的 C 数组指针

c++ - Lua + SWIG 猴子补丁

python - 如何在不编写代码的情况下在 amazon sqs 中实现指数退避

python - python 格式说明符中的变量

python - 在 Python 中删除一个对象和对它的所有引用?