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?
To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>(float original); Template arguments may be omitted when the compiler can infer them.
The act of creating a new definition of a function, class, or member of a class from a template declaration and one or more template arguments is called template instantiation.
Class template instantiationIn order for any code to appear, a template must be instantiated: the template arguments must be provided so that the compiler can generate an actual class (or function, from a function template).
A template is a simple yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types.
Declare instances of the member templates first, then declare instances of the class templates.
%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
Reference: 6.18 Templates (search for "member template") in the SWIG 2.0 Documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With