9

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?

Stefano Borini
  • 138,652
  • 96
  • 297
  • 431

1 Answers1

12

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.

Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • It works really great, but how do you instantiate member function of multiple instances, say Whatever::foo and Whatever::foo. For me it always ends up with the latter. – Jens Munk May 08 '15 at 20:14
  • @JensMunk, did you make sure to give each `%template` a different unique name? – Mark Tolonen May 08 '15 at 20:22
  • Unfortunately, this was not the error. I use an older version of SWIG, so I will not comment on this further – Jens Munk Aug 21 '16 at 08:40