20 November 2009

SWIG and Traits classes

With all the new code I've been writing—namely, a large number of classes and template parameters and typedefs—I've been using a number of traits classes. This unfortunately posed a problem for SWIG (which provides a Python front-end to the C++ code), because it had trouble deducing the true object types through the maze (albeit short) of inheritance, typedefs, and template parameters. It had trouble despite the %include "Traits.hpp" command, which makes it aware of the traits class with template parameters.

My first solution was to wrap the troublesome traits-derived typenames with #if SWIG [explicitly substitute types] #else [use normal traits] #endif. It nullified a subset of the purpose of the traits class, but it did the job well enough.

The problem cropped up again today with a new class. Frustrated, I cast about for a solution, and tried explicitly instantiating the template in SWIG with %template(TraitsT) Traits<OneD, Gray>;. To my surprise, it worked! So apparently it's necessary to instantiate a traits class (even if it is a struct with no methods or data) in order to get SWIG to properly parse the typedefs in classes that use those traits.

EDIT: Looks like the manual actually has an entry about this. It recommends %template() traits<double,double>; to avoid generating unnecessary wrappers for it.


Post a Comment