swig: extending a class template to provide __str__
Question: Say you have a template class `Foo`, and you want to wrap it with Swig
transparently so that you can print the class:

    
    
    >>> from example import *
    >>> f = Foo2()
    >>> print(f)
    In Foo class!
    

I have followed [this post](http://stackoverflow.com/questions/2548779/how-to-
stringfy-a-swig-matrix-object-in-python) and [this
one](http://www.swig.org/Doc1.3/SWIGPlus.html#SWIGPlus_class_extension). So my
header file is:

    
    
    #include <iostream>
    
    template <int d> class Foo {
    
    public:
    
      friend std::ostream &operator<<(std::ostream &os, const Foo &m) {
        os << "Inside Foo class!" << std::endl;
        return os;
      }
    };
    

And my interface file:

    
    
    %{
    #include <sstream>
    #include <iostream>
    #include "foo.hpp"
    %}
    
    %include "std_iostream.i"
    
    // Try grabbing it unmodified
    %include "foo.hpp"
    
    
    /* Instantiate a few different versions of the template */
    %template(Foo2) Foo<2>;
    %template(Foo3) Foo<3>;
    
    
    %extend Foo<2> {
    
      const char *__str__() {
    
        std::ostringstream oss(std::ostringstream::out);
        oss << *self;
        return oss.str().c_str();
      }
    };
    

So this works just fine, I can print the object as before, but I would like to
generalize it for any value of the template parameter, as it doesn't make
sense to copy that code for every template parameter. I tried the following in
the interface file but it didn't work:

    
    
    template <int d> class Foo {
    
    public:
    
      %extend {
        const char *__str__() {
    
          std::ostringstream oss(std::ostringstream::out);
          oss << *self;
          return oss.str().c_str();
        }
      }
    };
    


Answer: You should be able to `%extend` the primary template, from outside its
definition, by omitting the template parameter list:

    
    
    %extend Foo {
      const char *__str__() {
        std::ostringstream oss(std::ostringstream::out);
        oss << *self;
        return oss.str().c_str();
      }
    };
    
    %template(Foo2) Foo<2>;
    %template(Foo3) Foo<3>;
    

* * *

Or you could use a SWIG macro to wrap and extend each specialization in one
go:

    
    
    %define WRAP_FOO(N)
    
      %template( Foo ## N ) Foo<N>;
    
      %extend Foo<N> {
        const char *__str__() {
          std::ostringstream oss(std::ostringstream::out);
          oss << *self;
          return oss.str().c_str();
        }
      };
    
    %enddef
    
    /* Instantiate a few different versions of the template */
    WRAP_FOO(2)
    WRAP_FOO(3)
    

**Note that in either case, you are causing undefined behaviour by returning
the result of`.c_str()` of a `std::string` which is destroyed before the
function returns.**

