简体   繁体   中英

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

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
// 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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