如何使用swig实例化模板类的模板方法? [英] How to instantiate a template method of a template class with swig?

查看:455
本文介绍了如何使用swig实例化模板类的模板方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中有一个类是模板类,并且这个类上的一个方法是在另一个占位符上模板

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



当我将这个类传送到swig文件时,

 %template(Whatever_MyT)Whatever< MyT> ;;不幸的是,当我尝试调用 foo 时,会出现这样的情况:
在Whatever_MyT的一个实例从python,我得到一个属性错误。我想我必须用

实例化成员函数

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

这是我将在C ++写的,但它不工作(我得到语法错误)



问题在哪里?

解决方案

声明成员的实例模板,然后声明类模板的实例。



示例



 %module x 

%inline%{
#include< iostream>
template< class T> class Whatever
{
T m;
public:
无论(T a):m(a){}
模板< class V> void foo(Va){std :: cout< m < < a<< std :: endl; }
};
%}

//成员模板
%template(fooi)Whatever :: foo< int> ;;
%template(food)Whatever :: foo< double> ;;
//类模板。每个将包含fooi和食品成员。
%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模板(搜索成员模板)中的 SWIG 2.0文档


I have a class in C++ which is a template class, and one method on this class is templated on another placeholder

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

%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. 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)

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    
%template(fooi) Whatever::foo<int>;
%template(food) Whatever::foo<double>;
// class templates.  Each will contain fooi and food members.
%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.

这篇关于如何使用swig实例化模板类的模板方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆