1

I want to convert some C++ code to Java code in SWIG. In some C++ templates, there are some math operation about templates' parameters. Such as:

template<size_t nbits, size_t es>
  value<1 + 2 * (nbits - es)> fma(const posit<nbits, es>& a, const posit<nbits, es>& b, const posit<nbits, es>& c);

The parameters, nbits and es, are used to calculate the parameters of template class value<...>. When I want to use %template(...) to instantiate the template function, fma, like this:

%template(fma_32_2) sw::unum::fma<32,2>;

However, it fails and display:

error: 'nbits' was not declared in this scope
   SwigValueWrapper< sw::unum::value< 1+2*(nbits-es) > > result;
                                           ^~~~~
error: 'es' was not declared in this scope
   SwigValueWrapper< sw::unum::value< 1+2*(nbits-es) > > result;
                                                 ^~
error: template argument 1 is invalid
   SwigValueWrapper< sw::unum::value< 1+2*(nbits-es) > > result;
                                                     ^
error: template argument 1 is invalid
   SwigValueWrapper< sw::unum::value< 1+2*(nbits-es) > > result;

So, is there any ways to fix it?

MK.Bin
  • 73
  • 6
  • You also need to explicit instantiate posit using `%template`. Try to work it out from inside out. – Jens Munk May 27 '19 at 09:11
  • It doesn't work, too. It seems that swig can't resolve the mathematics operation of template parameters. – MK.Bin May 29 '19 at 07:27
  • That could very well be - SWIG is using its own parser. My recommendation is to expose SWIG to header files, which does not rely too heavily on compiler generated types - preferably only POD types. – Jens Munk May 29 '19 at 13:02
  • SWIG"s C++ template support tends to break down around this point. Normally it can be worked around, either by lying, default template arguments or some other trickery to make it produce valid Java/Python that matches up to what you're hoping. To show you how to do that though we're going to need to see enough detail to understand what the template parameter is being used for and how it's being used, otherwise the question isn't really answerable. – Flexo Jun 06 '19 at 07:05
  • I'm attempting to convert the C++ code of posit(https://github.com/stillwater-sc/universal/blob/master/posit/posit.hpp line 2586 & 2635) to Java code. Posit is a new type floating-point number, whose width and exponent bits are parameterized. So there are two template parameters, nbits and es. And according to nbits and es, the result width of one function can be calculated, which is 1 + 2 * (nbits - es). However, using %template(...) won't relate with this calculation. So, swig cannot recognize nbits and es in the expression 1 + 2 * (nbits - es). – MK.Bin Jun 07 '19 at 12:33

0 Answers0