3 <title>SWIG:Examples:java:template</title>
6 <body bgcolor="#ffffff">
9 <tt>SWIG/Examples/java/template/</tt>
12 <H2>C++ template support</H2>
15 This example illustrates how C++ templates can be used from Java using SWIG.
19 Lets take a templated function and a templated class as follows:
23 /* File : example.h */
25 // Some template definitions
27 template<class T> T max(T a, T b) { return a>b ? a : b; }
29 template<class T> class vector {
37 T &get(int index) {
40 void set(int index, T &val) {
45 T getitem(int index) {
46 return self->get(index);
48 void setitem(int index, T val) {
49 self->set(index,val);
56 The %addmethods is used for a neater interface from Java as the functions <tt>get</tt> and <tt>set</tt> use C++ references to primitive types. These are tricky to use from Java as they end up as a pointer in Java (Java long).
58 <h2>The SWIG interface</h2>
60 A simple SWIG interface for this can be built by simply grabbing the header file
65 /* File : example.i */
72 /* Let's just grab the original header file here */
75 /* Now instantiate some specific template declarations */
77 %template(maxint) max<int>;
78 %template(maxdouble) max<double>;
79 %template(vecint) vector<int>;
80 %template(vecdouble) vector<double>;
84 Note that SWIG parses the templated function <tt>max</tt> and templated class <tt>vector</tt> and so knows about them. However to generate code for use from Java, SWIG has to be told which class/type to use as the template parameter. The SWIG directive %template is used for this.
86 <h2>A sample Java program</h2>
88 Click <a href="runme.java">here</a> to see a Java program that calls the C++ functions from Java.
91 Use templated classes just like you would any other SWIG generated Java class. Use the classnames specified by the %template directive.
95 vecdouble dv = new vecdouble(1000);
96 dv.setitem(i, 12.34));