简体   繁体   English

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

[英]How to instantiate a template method of a template class with swig?

I have a class in C++ which is a template class, and one method on this class is templated on another placeholder 我有一个C ++类,它是一个模板类,这个类上的一个方法是在另一个占位符上模板化的

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

When I transport this class to the swig file, I did 当我将这个类传输到swig文件时,我做到了

%template(Whatever_MyT) Whatever<MyT>;

Unfortunately, when I try to invoke foo on an instance of Whatever_MyT from python, I get an attribute error. 不幸的是,当我尝试从python的Whatever_MyT实例上调用foo时,我得到一个属性错误。 I thought I had to instantiate the member function with 我以为我必须实例化成员函数

%template(foo_double) Whatever<MyT>::foo<double>;

which is what I would write in C++, but it does not work (I get a syntax error) 这是我在C ++中编写的,但它不起作用(我得到语法错误)

Where is the problem? 问题出在哪儿?

Declare instances of the member templates first, then declare instances of the class templates. 首先声明成员模板的实例,然后声明类模板的实例。

Example

%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>;

Output 产量

>>> 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 for "member template") in the SWIG 2.0 Documentation . 参考: 6.18 SWIG 2.0文档中的模板 (搜索“成员模板”)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM