Demaunt
Demaunt

Reputation: 1243

swig python template functions with type deduction

I want to wrap following C++ code into python module.

class minimal
{
public:
    minimal()
    {
    }
    ~minimal()
    {
    }

    template<class T>
    void foo(T a)
    {
        auto z = a; 
    }
};

As you can see, I have template function, and I know that I can't call templated function in Python, however I hope that calling foo with int or string arguments will be succesfull because of type deduction. Still there is no foo in the .cxx file, but SWIG documentation says, that it supports type deduction

So my goal is to python codeworking like this:

#C++ analog: minimal.foo(123)
minimal().foo(123) 

#C++: to minimal().foo(0.1)
minimal().foo(0.1) 

Is it possible? Or my idea is completly wrong?

Upvotes: 1

Views: 298

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177735

Use the %template directive to instruct SWIG to create implementations of particular templates. Only the template instances declared will be available.

Example:

%module test

%inline %{

class minimal
{
public:
    minimal()
    {
    }
    ~minimal()
    {
    }

    template<class T>
    void foo(T a)
    {
        auto z = a; 
    }
};

%}

%template(foo) minimal::foo<int>;
%template(foo) minimal::foo<double>;

Example:

>>> import test
>>> m=test.minimal()
>>> m.foo(1)
>>> m.foo(1.5)
>>> m.foo('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\test.py", line 115, in foo
    return _test.minimal_foo(self, *args)
NotImplementedError: Wrong number or type of arguments for overloaded function 'minimal_foo'.
  Possible C/C++ prototypes are:
    minimal::foo< int >(int)
    minimal::foo< double >(double)

Upvotes: 1

Related Questions