Menu

#1198 numeric template arguments do not get evaluated

open
nobody
5
2022-03-09
2011-10-14
No

In some cases, swig 2.0.4 doesn't fill in a numeric template argument when instantiating a template. This seems only to occur when doing calculations on the argument.

Example C++ code
---------------------- test.h
// just a class to get it going
template <int n>
class A
{ public:
A() {}
};

template <int n>
class B : public A<n-1 > ///// here using n-1
{
public:
B(const A<n-1 >& range);
};
--------------------------

----------- test.i
%module
%include "test.h"
%template(A0) A<0>;
%template(B1) B<1>;
---------

This generates a wrapper which fails to compile and looks like

----------------------------- test_wrap.cxx
SWIGINTERN PyObject *_wrap_new_B1(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
A< n-1 > *arg1 = 0 ; /////////////// ERROR here: still using n-1 as opposed 1-1
void *argp1 = 0 ;
int res1 = 0 ;
PyObject * obj0 = 0 ;
B< 1 > *result = 0 ;
Etc
}

-----------------------------

This seems a more complicated example of the (closed) bug
<http://sourceforge.net/tracker/index.php?func=detail&aid=775989&group_id=1645&atid=101645>
(Indeed, when using A<n> in the above example, everything works)

Discussion

  • William Fulton

    William Fulton - 2011-10-14

    The expansion is failing in Swig_cparse_template_expand(). An expression evaluator needs to be added to SWIG in order to expand these integral constant expression template parameters (listed under template non-type arguments in the standard). If existing evaluator code/library can be used, it wouldn't be too much extra work to use it.

    Suggested workaround is to add template specializations to SWIG so that the template parameters do not need to be evaluated, eg:

    template <>
    class B<1> : public A<0>
    {
    public:
    B(const A<0>& range) {}
    };

     
  • Olly Betts

    Olly Betts - 2022-03-09

    If existing evaluator code/library can be used, it wouldn't be too much extra work to use it.

    SWIG actually contains an integral constant expression evaluation already - it's currently used for expressions in preprocessor conditionals: Source/Preprocessor/expr.c

     

Log in to post a comment.