import source from 1.3.40
[external/swig.git] / Doc / Manual / SWIGPlus.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html>
3 <head>
4 <title>SWIG and C++</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
6 </head>
7
8 <body bgcolor="#ffffff">
9 <H1><a name="SWIGPlus"></a>6 SWIG and C++</H1>
10 <!-- INDEX -->
11 <div class="sectiontoc">
12 <ul>
13 <li><a href="#SWIGPlus_nn2">Comments on C++ Wrapping</a>
14 <li><a href="#SWIGPlus_nn3">Approach</a>
15 <li><a href="#SWIGPlus_nn4">Supported C++ features</a>
16 <li><a href="#SWIGPlus_nn5">Command line options and compilation</a>
17 <li><a href="#SWIGPlus_nn38">Proxy classes</a>
18 <ul>
19 <li><a href="#SWIGPlus_nn39">Construction of proxy classes</a>
20 <li><a href="#SWIGPlus_nn40">Resource management in proxies</a>
21 <li><a href="#SWIGPlus_nn41">Language specific details</a>
22 </ul>
23 <li><a href="#SWIGPlus_nn6">Simple C++ wrapping</a>
24 <ul>
25 <li><a href="#SWIGPlus_nn7">Constructors and destructors</a>
26 <li><a href="#SWIGPlus_nn8">Default constructors, copy constructors and implicit destructors</a>
27 <li><a href="#SWIGPlus_nn9">When constructor wrappers aren't created</a>
28 <li><a href="#SWIGPlus_nn10">Copy constructors</a>
29 <li><a href="#SWIGPlus_nn11">Member functions</a>
30 <li><a href="#SWIGPlus_nn12">Static members</a>
31 <li><a href="#SWIGPlus_member_data">Member data</a>
32 </ul>
33 <li><a href="#SWIGPlus_default_args">Default arguments</a>
34 <li><a href="#SWIGPlus_nn15">Protection</a>
35 <li><a href="#SWIGPlus_nn16">Enums and constants</a>
36 <li><a href="#SWIGPlus_nn17">Friends</a>
37 <li><a href="#SWIGPlus_nn18">References and pointers</a>
38 <li><a href="#SWIGPlus_nn19">Pass and return by value</a>
39 <li><a href="#SWIGPlus_nn20">Inheritance</a>
40 <li><a href="#SWIGPlus_nn21">A brief discussion of multiple inheritance, pointers,  and type checking</a>
41 <li><a href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions and Methods</a>
42 <ul>
43 <li><a href="#SWIGPlus_nn24">Dispatch function generation</a>
44 <li><a href="#SWIGPlus_nn25">Ambiguity in Overloading</a>
45 <li><a href="#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a>
46 <li><a href="#SWIGPlus_nn27">Comments on overloading</a>
47 </ul>
48 <li><a href="#SWIGPlus_nn28">Wrapping overloaded operators</a>
49 <li><a href="#SWIGPlus_class_extension">Class extension</a>
50 <li><a href="#SWIGPlus_nn30">Templates</a>
51 <li><a href="#SWIGPlus_nn31">Namespaces</a>
52 <li><a href="#SWIGPlus_renaming_templated_types_namespaces">Renaming templated types in namespaces</a>
53 <li><a href="#SWIGPlus_exception_specifications">Exception specifications</a>
54 <li><a href="#SWIGPlus_catches">Exception handling with %catches</a>
55 <li><a href="#SWIGPlus_nn33">Pointers to Members</a>
56 <li><a href="#SWIGPlus_nn34">Smart pointers and operator-&gt;()</a>
57 <li><a href="#SWIGPlus_nn35">Using declarations and inheritance</a>
58 <li><a href="#SWIGPlus_nested_classes">Nested classes</a>
59 <li><a href="#SWIGPlus_nn37">A brief rant about const-correctness</a>
60 <li><a href="#SWIGPlus_nn42">Where to go for more information</a>
61 </ul>
62 </div>
63 <!-- INDEX -->
64
65
66
67 <p>
68 This chapter describes SWIG's support for wrapping C++.  As a prerequisite,
69 you should first read the chapter <a href="SWIG.html#SWIG">SWIG Basics</a> to see
70 how SWIG wraps ANSI C.  Support for C++ builds upon ANSI C
71 wrapping and that material will be useful in understanding this chapter.
72 </p>
73
74 <H2><a name="SWIGPlus_nn2"></a>6.1 Comments on C++ Wrapping</H2>
75
76
77 <p>
78 Because of its complexity and the fact that C++ can be
79 difficult to integrate with itself let alone other languages, SWIG 
80 only provides support for a subset of C++ features.   Fortunately, 
81 this is now a rather large subset.  
82 </p>
83
84 <p>
85 In part, the problem with C++ wrapping is that there is no
86 semantically obvious (or automatic ) way to map many of its advanced
87 features into other languages.  As a simple example, consider the
88 problem of wrapping C++ multiple inheritance to a target language with
89 no such support.  Similarly, the use of overloaded operators and
90 overloaded functions can be problematic when no such capability exists
91 in a target language.
92 </p>
93
94 <p>
95 A more subtle issue with C++ has to do with the way that some C++
96 programmers think about programming libraries.  In the world of SWIG,
97 you are really trying to create binary-level software components for
98 use in other languages.  In order for this to work, a "component" has
99 to contain real executable instructions and there has to be some kind
100 of binary linking mechanism for accessing its functionality.  In
101 contrast, C++ has increasingly relied upon generic programming and
102 templates for much of its functionality.
103 Although templates are a powerful feature, they are largely orthogonal
104 to the whole notion of binary components and libraries.  For example,
105 an STL <tt>vector</tt> does not define any kind of binary object for
106 which SWIG can just create a wrapper.  To further complicate matters,
107 these libraries often utilize a lot of behind the scenes magic in
108 which the semantics of seemingly basic operations (e.g., pointer
109 dereferencing, procedure call, etc.) can be changed in dramatic and
110 sometimes non-obvious ways.  Although this "magic" may present few
111 problems in a C++-only universe, it greatly complicates the problem of
112 crossing language boundaries and provides many opportunities to shoot
113 yourself in the foot.  You will just have to be careful.
114 </p>
115
116 <H2><a name="SWIGPlus_nn3"></a>6.2 Approach</H2>
117
118
119 <p>
120 To wrap C++, SWIG uses a layered approach to code generation.  
121 At the lowest level, SWIG generates a collection of procedural ANSI-C style
122 wrappers.   These wrappers take care of basic type conversion,
123 type checking, error handling, and other low-level details of the C++ binding.
124 These wrappers are also sufficient to bind C++ into any target language
125 that supports built-in procedures.   In some sense, you might view this
126 layer of wrapping as providing a C library interface to C++.
127 On top of the low-level procedural (flattened) interface, SWIG generates proxy classes 
128 that provide a natural object-oriented (OO) interface to the underlying code.  The proxy classes are typically
129 written in the target language itself.  For instance, in Python, a real
130 Python class is used to provide a wrapper around the underlying C++ object.
131 </p>
132
133 <p>
134 It is important to emphasize that SWIG takes a deliberately
135 conservative and non-intrusive approach to C++ wrapping. SWIG does not
136 encapsulate C++ classes inside a special C++ adaptor, it does not rely
137 upon templates, nor does it add in additional C++ inheritance when
138 generating wrappers.  The last thing that most C++ programs need is
139 even more compiler magic.  Therefore, SWIG tries to maintain a very
140 strict and clean separation between the implementation of your C++
141 application and the resulting wrapper code. You might say that SWIG
142 has been written to follow the principle of least surprise--it does
143 not play sneaky tricks with the C++ type system, it doesn't mess with
144 your class hierarchies, and it doesn't introduce new semantics.
145 Although this approach might not provide the most seamless integration
146 with C++, it is safe, simple, portable, and debuggable.
147 </p>
148
149 <p>
150 Some of this chapter focuses on the low-level procedural interface to
151 C++ that is used as the foundation for all language modules.  Keep in
152 mind that the target languages also provide the high-level OO interface via
153 proxy classes.  More detailed coverage can be found in the documentation
154 for each target language.
155 </p>
156
157 <H2><a name="SWIGPlus_nn4"></a>6.3 Supported C++ features</H2>
158
159
160 <p>
161 SWIG currently supports most C++ features including the following:</p>
162
163 <ul>
164 <li>Classes
165 <li>Constructors and destructors
166 <li>Virtual functions
167 <li>Public inheritance (including multiple inheritance)
168 <li>Static functions
169 <li>Function and method overloading
170 <li>Operator overloading for many standard operators
171 <li>References
172 <li>Templates (including specialization and member templates)
173 <li>Pointers to members
174 <li>Namespaces
175 <li>Default parameters
176 <li>Smart pointers
177 </ul>
178
179 <p>
180 The following C++ features are not currently supported:</p>
181
182 <ul>
183 <li>Overloaded versions of certain operators (new, delete, etc.)
184 <li>Nested classes, see <a href="#SWIGPlus_nested_classes">Nested classes</a> for workarounds.
185 </ul>
186
187 <p>
188 As a rule of thumb, SWIG should not be used on raw C++ source files, use header files only.
189 </p>
190
191 <p>
192 SWIG's C++ support is an ongoing project so some of these limitations may be lifted
193 in future releases.  However, we make no promises.  Also, submitting a bug report is a very
194 good way to get problems fixed (wink).
195 </p>
196
197 <H2><a name="SWIGPlus_nn5"></a>6.4 Command line options and compilation</H2>
198
199
200 <p>
201 When wrapping C++ code, it is critical that SWIG be called with the
202 `<tt>-c++</tt>' option. This changes the way a number of critical
203 features such as memory management are handled. It
204 also enables the recognition of C++ keywords. Without the <tt>-c++</tt>
205 flag, SWIG will either issue a warning or a large number of syntax
206 errors if it encounters C++ code in an interface file.</p>
207
208 <p>
209 When compiling and linking the resulting wrapper file,  it is normal
210 to use the C++ compiler.  For example:
211 </p>
212
213 <div class="shell">
214 <pre>
215 $ swig -c++ -tcl example.i
216 $ c++ -c example_wrap.cxx 
217 $ c++ example_wrap.o $(OBJS) -o example.so
218 </pre>
219 </div>
220
221 <p>
222 Unfortunately, the process varies slightly on each platform.  Make sure
223 you refer to the documentation on each target language for further
224 details.  The SWIG Wiki also has further details.
225 </p>
226
227 <b>Compatibility Note:</b> Early versions of SWIG generated just a flattened low-level C style API to C++ classes by default.
228 The <tt>-noproxy</tt> commandline option is recognised by many target languages and will generate just this
229 interface as in earlier versions.
230
231 <H2><a name="SWIGPlus_nn38"></a>6.5 Proxy classes</H2>
232
233
234 <p>
235 In order to provide a natural mapping from C++ classes to the target language classes, SWIG's target
236 languages mostly wrap C++ classes with special proxy classes.  These
237 proxy classes are typically implemented in the target language itself.
238 For example, if you're building a Python module, each C++ class is
239 wrapped by a Python proxy class.  Or if you're building a Java module, each
240 C++ class is wrapped by a Java proxy class.  
241 </p>
242
243 <H3><a name="SWIGPlus_nn39"></a>6.5.1 Construction of proxy classes</H3>
244
245
246 <p>
247 Proxy classes are always constructed as an extra layer of wrapping that uses low-level
248 accessor functions.  To illustrate, suppose you had a
249 C++ class like this:
250 </p>
251
252 <div class="code">
253 <pre>
254 class Foo {
255 public:
256       Foo();
257      ~Foo();
258       int  bar(int x);
259       int  x;
260 };
261 </pre>
262 </div>
263
264 <p>
265 Using C++ as pseudocode, a proxy class looks something like this:
266 </p>
267
268 <div class="code">
269 <pre>
270 class FooProxy {
271 private:
272       Foo    *self;
273 public:
274       FooProxy() {
275             self = new_Foo();
276       }
277      ~FooProxy() {
278             delete_Foo(self);
279       }
280       int bar(int x) {
281             return Foo_bar(self,x);
282       }
283       int x_get() {
284             return Foo_x_get(self);
285       }
286       void x_set(int x) {
287             Foo_x_set(self,x);
288       }
289 };
290 </pre>
291 </div>
292
293 <p>
294 Of course, always keep in mind that the real proxy class is written in the target language.
295 For example, in Python, the proxy might look roughly like this:
296 </p>
297
298 <div class="targetlang">
299 <pre>
300 class Foo:
301     def __init__(self):
302          self.this = new_Foo()
303     def __del__(self):
304          delete_Foo(self.this)
305     def bar(self,x):
306          return Foo_bar(self.this,x)
307     def __getattr__(self,name):
308          if name == 'x':
309               return Foo_x_get(self.this)
310          ...
311     def __setattr__(self,name,value):
312          if name == 'x':
313               Foo_x_set(self.this,value)
314          ...
315 </pre>
316 </div>
317
318 <p>
319 Again, it's important to emphasize that the low-level accessor functions are always used by the
320 proxy classes.
321 Whenever possible, proxies try to take advantage of language features that are similar to C++.  This
322 might include operator overloading,  exception handling, and other features.
323 </p>
324
325 <H3><a name="SWIGPlus_nn40"></a>6.5.2 Resource management in proxies</H3>
326
327
328 <p>
329 A major issue with proxies concerns the memory management of wrapped objects.   Consider the following
330 C++ code:
331 </p>
332
333 <div class="code">
334 <pre>
335 class Foo {
336 public:
337       Foo();
338      ~Foo();
339       int bar(int x);
340       int x;
341 };
342
343 class Spam {
344 public:
345       Foo *value;
346       ...
347 };
348 </pre>
349 </div>
350
351 <p>
352 Consider some script code that uses these classes:
353 </p>
354
355 <div class="targetlang">
356 <pre>
357 f = Foo()               # Creates a new Foo
358 s = Spam()              # Creates a new Spam
359 s.value = f             # Stores a reference to f inside s
360 g = s.value             # Returns stored reference
361 g = 4                   # Reassign g to some other value
362 del f                   # Destroy f 
363 </pre>
364 </div>
365
366 <p>
367 Now, ponder the resulting memory management issues.  When objects are
368 created in the script, the objects are wrapped by newly created proxy
369 classes.  That is, there is both a new proxy class instance and a new
370 instance of the underlying C++ class.  In this example, both
371 <tt>f</tt> and <tt>s</tt> are created in this way.  However, the
372 statement <tt>s.value</tt> is rather curious---when executed, a
373 pointer to <tt>f</tt> is stored inside another object.  This means
374 that the scripting proxy class <em>AND</em> another C++ class share a
375 reference to the same object.  To make matters even more interesting,
376 consider the statement <tt>g = s.value</tt>.  When executed, this
377 creates a new proxy class <tt>g</tt> that provides a wrapper around the
378 C++ object stored in <tt>s.value</tt>.  In general, there is no way to
379 know where this object came from---it could have been created by the
380 script, but it could also have been generated internally.  In this
381 particular example, the assignment of <tt>g</tt> results in a second
382 proxy class for <tt>f</tt>.  In other words, a reference to <tt>f</tt>
383 is now shared by two proxy classes <em>and</em> a C++ class.   
384 </p>
385
386 <p>
387 Finally, consider what happens when objects are destroyed.  In the
388 statement, <tt>g=4</tt>, the variable <tt>g</tt> is reassigned.  In
389 many languages, this makes the old value of <tt>g</tt> available for
390 garbage collection.  Therefore, this causes one of the proxy classes
391 to be destroyed.  Later on, the statement <tt>del f</tt> destroys the
392 other proxy class.  Of course, there is still a reference to the
393 original object stored inside another C++ object.  What happens to it?
394 Is the object still valid?
395 </p>
396
397 <p>
398 To deal with memory management problems, proxy classes provide an API
399 for controlling ownership.  In C++ pseudocode, ownership control might look
400 roughly like this:
401 </p>
402
403 <div class="code">
404 <pre>
405 class FooProxy {
406 public:
407       Foo    *self;
408       int     thisown;
409
410       FooProxy() {
411             self = new_Foo();
412             thisown = 1;       // Newly created object
413       }
414      ~FooProxy() {
415             if (thisown) delete_Foo(self);
416       }
417       ...
418       // Ownership control API
419       void disown() {
420            thisown = 0;
421       }
422       void acquire() {
423            thisown = 1;
424       }
425 };
426
427 class FooPtrProxy: public FooProxy {
428 public:
429       FooPtrProxy(Foo *s) {
430           self = s;
431           thisown = 0;
432       }
433 };
434
435 class SpamProxy {
436      ...
437      FooProxy *value_get() {
438           return FooPtrProxy(Spam_value_get(self));
439      }
440      void value_set(FooProxy *v) {
441           Spam_value_set(self,v-&gt;self);
442           v-&gt;disown();
443      }
444      ...
445 };
446 </pre>
447 </div>
448
449 <p>
450 Looking at this code, there are a few central features:
451 </p>
452
453 <ul>
454 <li>Each proxy class keeps an extra flag to indicate ownership.  C++ objects are only destroyed
455 if the ownership flag is set.
456 </li>
457
458 <li>When new objects are created in the target language, the ownership flag is set.
459 </li>
460
461 <li>When a reference to an internal C++ object is returned, it is wrapped by a proxy
462 class, but the proxy class does not have ownership.  
463 </li>
464
465 <li>In certain cases, ownership is adjusted.  For instance, when a value is assigned to the member of
466 a class, ownership is lost.
467 </li>
468
469 <li>Manual ownership control is provided by special <tt>disown()</tt> and <tt>acquire()</tt> methods.
470 </li>
471 </ul>
472
473 <p>
474 Given the tricky nature of C++ memory management, it is impossible for proxy classes to automatically handle
475 every possible memory management problem.  However, proxies do provide a mechanism for manual control that
476 can be used (if necessary) to address some of the more tricky memory management problems.
477 </p>
478
479 <H3><a name="SWIGPlus_nn41"></a>6.5.3 Language specific details</H3>
480
481
482 <p>
483 Language specific details on proxy classes are contained in the chapters describing each target language.  This
484 chapter has merely introduced the topic in a very general way.
485 </p>
486
487 <H2><a name="SWIGPlus_nn6"></a>6.6 Simple C++ wrapping</H2>
488
489
490 <p>
491 The following code shows a SWIG interface file for a simple C++
492 class.</p>
493
494 <div class="code"><pre>
495 %module list
496 %{
497 #include "list.h"
498 %}
499
500 // Very simple C++ example for linked list
501
502 class List {
503 public:
504   List();
505   ~List();
506   int  search(char *value);
507   void insert(char *);
508   void remove(char *);
509   char *get(int n);
510   int  length;
511 static void print(List *l);
512 };
513 </pre></div>
514
515 <p>
516 To generate wrappers for this class, SWIG first reduces the class to a collection of low-level C-style
517 accessor functions which are then used by the proxy classes.
518 </p>
519
520 <H3><a name="SWIGPlus_nn7"></a>6.6.1 Constructors and destructors</H3>
521
522
523 <p>
524 C++ constructors and destructors are translated into accessor
525 functions such as the following :</p>
526
527 <div class="code"><pre>
528 List * new_List(void) {
529         return new List;
530 }
531 void delete_List(List *l) {
532         delete l;
533 }
534
535 </pre></div>
536
537 <H3><a name="SWIGPlus_nn8"></a>6.6.2 Default constructors, copy constructors and implicit destructors</H3>
538
539
540 <p>
541 Following the C++ rules for implicit constructor and destructors, SWIG
542 will automatically assume there is one even when they are not
543 explicitly declared in the class interface.
544 </p>
545
546 <p>
547 In general then:
548 </p>
549
550 <ul>
551 <li>
552 If a C++ class does not declare any explicit constructor, SWIG will
553 automatically generate a wrapper for one.
554 </li>
555
556 <li>
557 If a C++ class does not declare an explicit copy constructor, SWIG will
558 automatically generate a wrapper for one if the <tt>%copyctor</tt> is used.
559 </li>
560
561 <li>
562 If a C++ class does not declare an explicit destructor, SWIG will
563 automatically generate a wrapper for one.
564 </li>
565 </ul>
566
567 <p>
568  And as in C++, a few rules that alters the previous behavior:
569 </p>
570
571 <ul>
572 <li>A default constructor is not created if a class already defines a constructor with arguments.
573 </li>
574
575 <li>Default constructors are not generated for classes with pure virtual methods or for classes that
576 inherit from an abstract class, but don't provide definitions for all of the pure methods.
577 </li>
578
579 <li>A default constructor is not created unless all base classes support a 
580 default constructor. 
581 </li>
582
583 <li>Default constructors and implicit destructors are not created if a class
584 defines them in a <tt>private</tt> or <tt>protected</tt> section.
585 </li>
586
587 <li>Default constructors and implicit destructors are not created if any base
588 class defines a non-public default constructor or destructor.
589 </li>
590 </ul>
591
592 <p>
593 SWIG should never generate a default constructor, copy constructor or
594 default destructor wrapper for a class in which it is illegal to do so.  In
595 some cases, however, it could be necessary (if the complete class
596 declaration is not visible from SWIG, and one of the above rules is
597 violated) or desired (to reduce the size of the final interface) by
598 manually disabling the implicit constructor/destructor generation.
599 </p>
600
601 <p>
602 To manually disable these, the <tt>%nodefaultctor</tt> and <tt>%nodefaultdtor</tt>
603 <a href="Customization.html#Customization_feature_flags">feature flag</a> directives
604 can be used. Note that these directives only affects the
605 implicit generation, and they have no effect if the default/copy
606 constructors or destructor are explicitly declared in the class
607 interface.
608 </p>
609
610 <p>
611 For example:
612 </p>
613
614 <div class="code">
615 <pre>
616 %nodefaultctor Foo;  // Disable the default constructor for class Foo.
617 class Foo {          // No default constructor is generated, unless one is declared
618 ...
619 };
620 class Bar {          // A default constructor is generated, if possible
621 ...
622 };
623 </pre>
624 </div>
625
626 <p>
627 The directive <tt>%nodefaultctor</tt> can also be applied "globally", as in:
628 </p>
629
630 <div class="code">
631 <pre>
632 %nodefaultctor; // Disable creation of default constructors
633 class Foo {     // No default constructor is generated, unless one is declared
634 ...
635 };
636 class Bar {   
637 public:
638   Bar();        // The default constructor is generated, since one is declared
639 };
640 %clearnodefaultctor; // Enable the creation of default constructors again
641 </pre>
642 </div>
643
644 <p>
645 The corresponding <tt>%nodefaultdtor</tt> directive can be used
646 to disable the generation of the default or implicit destructor, if
647 needed. Be aware, however, that this could lead to memory leaks in the
648 target language. Hence, it is recommended to use this directive only
649 in well known cases. For example:
650 </p>
651
652 <div class="code">
653 <pre>
654 %nodefaultdtor Foo;   // Disable the implicit/default destructor for class Foo.
655 class Foo {           // No destructor is generated, unless one is declared
656 ...
657 };
658 </pre>
659 </div>
660
661 <p>
662 <b>Compatibility Note:</b> The generation of default
663 constructors/implicit destructors was made the default behavior in SWIG
664 1.3.7. This may break certain older modules, but the old behavior can
665 be easily restored using <tt>%nodefault</tt> or the
666 <tt>-nodefault</tt> command line option.  Furthermore, in order for
667 SWIG to properly generate (or not generate) default constructors, it
668 must be able to gather information from both the <tt>private</tt> and
669 <tt>protected</tt> sections (specifically, it needs to know if a private or
670 protected constructor/destructor is defined).   In older versions of
671 SWIG, it was fairly common to simply remove or comment out
672 the private and protected sections of a class due to parser limitations.
673 However, this removal may now cause SWIG to erroneously generate constructors
674 for classes that define a constructor in those sections.  Consider restoring
675 those sections in the interface or using <tt>%nodefault</tt> to fix the problem.
676 </p>
677
678 <p>
679 <b>Note:</b> The <tt>%nodefault</tt>
680 directive/<tt>-nodefault</tt> options described above, which disable both the default
681 constructor and the implicit destructors, could lead to memory
682 leaks, and so it is strongly recommended to not use them.
683 </p>
684
685
686 <H3><a name="SWIGPlus_nn9"></a>6.6.3 When constructor wrappers aren't created</H3>
687
688
689 <p>
690 If a class defines a constructor, SWIG normally tries to generate a wrapper for it.  However, SWIG will 
691 not generate a constructor wrapper if it thinks that it will result in illegal wrapper code.  There are really
692 two cases where this might show up.
693 </p>
694
695 <p>
696 First, SWIG won't generate wrappers for protected or private constructors.  For example:
697 </p>
698
699 <div class="code">
700 <pre>
701 class Foo {
702 protected:
703      Foo();         // Not wrapped.
704 public:
705       ...
706 };
707 </pre>
708 </div>
709
710 <p>
711 Next, SWIG won't generate wrappers for a class if it appears to be abstract--that is, it has undefined
712 pure virtual methods.  Here are some examples:
713 </p>
714
715 <div class="code">
716 <pre>
717 class Bar {
718 public:
719      Bar();               // Not wrapped.  Bar is abstract.
720      virtual void spam(void) = 0; 
721 };
722
723 class Grok : public Bar {
724 public:
725       Grok();            // Not wrapped. No implementation of abstract spam().
726 };
727 </pre>
728 </div>
729
730 <p>
731 Some users are surprised (or confused) to find missing constructor wrappers in their interfaces.  In almost 
732 all cases, this is caused when classes are determined to be abstract.   To see if this is the case, run SWIG with
733 all of its warnings turned on:
734 </p>
735
736 <div class="shell">
737 <pre>
738 % swig -Wall -python module.i
739 </pre>
740 </div>
741
742 <p>
743 In this mode, SWIG will issue a warning for all abstract classes.   It is possible to force a class to be
744 non-abstract using this:
745 </p>
746
747 <div class="code">
748 <pre>
749 %feature("notabstract") Foo;
750
751 class Foo : public Bar {
752 public:
753      Foo();    // Generated no matter what---not abstract. 
754      ...
755 };
756 </pre>
757 </div>
758
759 <p>
760 More information about <tt>%feature</tt> can be found in the <a href="Customization.html#Customization">Customization features</a> chapter.
761 </p>
762
763 <H3><a name="SWIGPlus_nn10"></a>6.6.4 Copy constructors</H3>
764
765
766 <p>
767 If a class defines more than one constructor, its behavior depends on the capabilities of the
768 target language.  If overloading is supported, the copy constructor is accessible using
769 the normal constructor function.  For example, if you have this:
770 </p>
771
772 <div class="code">
773 <pre>
774 class List {
775 public:
776     List();    
777     List(const List &amp;);      // Copy constructor
778     ...
779 };
780 </pre>
781 </div>
782
783 <p>
784 then the copy constructor can be used as follows:
785 </p>
786
787 <div class="targetlang">
788 <pre>
789 x = List()               # Create a list
790 y = List(x)              # Copy list x
791 </pre>
792 </div>
793
794 <p>
795 If the target language does not support overloading, then the copy constructor is available
796 through a special function like this:
797 </p>
798
799 <div class="code">
800 <pre>
801 List *copy_List(List *f) {
802     return new List(*f);
803 }
804 </pre>
805 </div>
806
807 <p>
808 <b>Note:</b> For a class <tt>X</tt>, SWIG only treats a constructor as
809 a copy constructor if it can be applied to an object of type
810 <tt>X</tt> or <tt>X *</tt>.  If more than one copy constructor is
811 defined, only the first definition that appears is used as the copy
812 constructor--other definitions will result in a name-clash.
813 Constructors such as <tt>X(const X &amp;)</tt>, <tt>X(X &amp;)</tt>, and
814 <tt>X(X *)</tt> are handled as copy constructors in SWIG.
815 </p>
816
817 <p>
818 <b>Note:</b> SWIG does <em>not</em> generate a copy constructor
819 wrapper unless one is explicitly declared in the class.  This differs
820 from the treatment of default constructors and destructors.
821 However, copy constructor wrappers can be generated if using the <tt>copyctor</tt>
822 <a href="Customization.html#Customization_feature_flags">feature flag</a>. For example:
823 </p>
824
825 <div class="code">
826 <pre>
827 %copyctor List;
828
829 class List {
830 public:
831     List();    
832 };
833 </pre>
834 </div>
835
836 <p>
837 Will generate a copy constructor wrapper for <tt>List</tt>.
838 </p>
839
840 <p>
841 <b>Compatibility note:</b> Special support for copy constructors was
842 not added until SWIG-1.3.12.  In previous versions, copy constructors
843 could be wrapped, but they had to be renamed.  For example:
844 </p>
845
846 <div class="code">
847 <pre>
848 class Foo {
849 public:
850     Foo();
851   %name(CopyFoo) Foo(const Foo &amp;);
852     ...
853 };
854 </pre>
855 </div>
856
857 <p>
858 For backwards compatibility, SWIG does not perform any special
859 copy-constructor handling if the constructor has been manually
860 renamed.  For instance, in the above example, the name of the
861 constructor is set to <tt>new_CopyFoo()</tt>.   This is the same as in 
862 older versions.
863 </p>
864
865 <H3><a name="SWIGPlus_nn11"></a>6.6.5 Member functions</H3>
866
867
868 <p>
869 All member functions are roughly translated into accessor functions like this :</p>
870
871 <div class="code"><pre>
872 int List_search(List *obj, char *value) {
873         return obj-&gt;search(value);
874 }
875
876 </pre></div>
877
878 <p>
879 This translation is the same even if the member function has been
880 declared as <tt>virtual</tt>.
881 </p>
882
883 <p>
884 It should be noted that SWIG does not <em>actually</em> create a C accessor
885 function in the code it generates.  Instead, member access such as
886 <tt>obj-&gt;search(value)</tt> is directly inlined into the generated
887 wrapper functions.  However, the name and calling convention of the
888 low-level procedural wrappers match the accessor function prototype described above.
889 </p>
890
891 <H3><a name="SWIGPlus_nn12"></a>6.6.6 Static members</H3>
892
893
894 <p>
895 Static member functions are called directly without making any special
896 transformations. For example, the static member function
897 <tt>print(List *l)</tt> directly invokes <tt>List::print(List *l)</tt>
898 in the generated wrapper code.
899 </p>
900
901 <H3><a name="SWIGPlus_member_data"></a>6.6.7 Member data</H3>
902
903
904 <p>
905 Member data is handled in exactly the same manner as for C
906 structures. A pair of accessor functions are effectively created. For example
907 :</p>
908
909 <div class="code"><pre>
910 int List_length_get(List *obj) {
911         return obj-&gt;length;
912 }
913 int List_length_set(List *obj, int value) {
914         obj-&gt;length = value;
915         return value;
916 }
917
918 </pre></div>
919
920 <p>
921 A read-only member can be created using the <tt>%immutable</tt> and <tt>%mutable</tt> 
922 <a href="Customization.html#Customization_feature_flags">feature flag</a> directive.
923 For example, we probably wouldn't want
924 the user to change the length of a list so we could do the following
925 to make the value available, but read-only.</p>
926
927 <div class="code"><pre>
928 class List {
929 public:
930 ...
931 %immutable;
932         int length;
933 %mutable;
934 ...
935 };
936 </pre></div>
937
938 <p>
939 Alternatively, you can specify an immutable member in advance like this:
940 </p>
941
942 <div class="code">
943 <pre>
944 %immutable List::length;
945 ...
946 class List {
947    ...
948    int length;         // Immutable by above directive
949    ...
950 };
951 </pre>
952 </div>
953
954 <p>
955 Similarly, all data attributes declared as <tt>const</tt> are wrapped as read-only members.
956 </p>
957
958 <p>
959 There are some subtle issues when wrapping data members that are
960 themselves classes.  For instance, if you had another class like this,
961 </p>
962
963 <div class="code">
964 <pre>
965 class Foo {
966 public:
967     List items;
968     ...
969 </pre>
970 </div>
971
972 <p>
973 then the low-level accessor to the <tt>items</tt> member actually uses pointers. For example:
974 </p>
975
976 <div class="code">
977 <pre>
978 List *Foo_items_get(Foo *self) {
979     return &amp;self-&gt;items;
980 }
981 void Foo_items_set(Foo *self, List *value) {
982     self-&gt;items = *value;
983 }
984 </pre>
985 </div>
986
987 <p>
988 More information about this can be found in the SWIG Basics chapter,
989 <a href="SWIG.html#SWIG_structure_data_members">Structure data members</a> section. 
990 </p>
991
992 <p>
993 The wrapper code to generate the accessors for classes comes from the pointer typemaps. 
994 This can be somewhat unnatural for some types.
995 For example, a user would expect the STL std::string class member variables to be wrapped as a string in the target language,
996 rather than a pointer to this class.
997 The const reference typemaps offer this type of marshalling, so there is a feature to tell SWIG to use the const reference typemaps rather than the pointer typemaps.
998 It is the <tt>%naturalvar</tt> directive and is used as follows:
999 </p>
1000
1001 <div class="code">
1002 <pre>
1003 // All List variables will use const List&amp; typemaps
1004 %naturalvar List;
1005
1006 // Only Foo::myList will use const List&amp; typemaps
1007 %naturalvar Foo::myList;
1008 struct Foo {
1009   List myList;
1010 };
1011
1012 // All variables will use const reference typemaps
1013 %naturalvar;
1014 </pre>
1015 </div>
1016
1017 <p>
1018 The observant reader will notice that <tt>%naturalvar</tt> works like any other
1019 <a href="Customization.html#Customization_feature_flags">feature flag</a> directive,
1020 except it can also be attached to class types.
1021 The first of the example usages above show <tt>%naturalvar</tt> attaching to the <tt>List</tt> class.
1022 Effectively this feature changes the way accessors are generated to the following:
1023 </p>
1024
1025 <div class="code">
1026 <pre>
1027 const List &amp;Foo_items_get(Foo *self) {
1028     return self-&gt;items;
1029 }
1030 void Foo_items_set(Foo *self, const List &amp;value) {
1031     self-&gt;items = value;
1032 }
1033 </pre>
1034 </div>
1035
1036 <p>
1037 In fact it is generally a good idea to use this feature globally as the reference typemaps have extra NULL checking compared to the pointer typemaps.
1038 A pointer can be NULL, whereas a reference cannot, so the extra checking ensures that the target language user does not pass in a value that translates
1039 to a NULL pointer and thereby preventing any potential NULL pointer dereferences.
1040 The <tt>%naturalvar</tt> feature will apply to global variables in addition to member variables in some language modules, eg C# and Java.
1041 </p>
1042
1043 <p>
1044 Other alternatives for turning this feature on globally are to use the <tt>swig -naturalvar</tt> commandline option 
1045 or the module mode option, <tt>%module(naturalvar=1)</tt>
1046 </p>
1047
1048 <p>
1049 <b>Compatibility note:</b> The <tt>%naturalvar</tt> feature was introduced in SWIG-1.3.28, prior to which it was necessary to manually apply the const reference
1050 typemaps, eg <tt>%apply const std::string &amp; { std::string * }</tt>, but this example would also apply the typemaps to methods taking a <tt>std::string</tt> pointer.
1051 </p>
1052
1053 <p>
1054 <b>Compatibility note:</b> Read-only access used to be controlled by a pair of directives
1055 <tt>%readonly</tt> and <tt>%readwrite</tt>.   Although these directives still work, they
1056 generate a warning message.   Simply change the directives to <tt>%immutable;</tt> and
1057 <tt>%mutable;</tt> to silence the warning.  Don't forget the extra semicolon!
1058 </p>
1059
1060 <p>
1061 <b>Compatibility note:</b> Prior to SWIG-1.3.12, all members of unknown type were
1062 wrapped into accessor functions using pointers.  For example, if you had a structure
1063 like this
1064 </p>
1065
1066 <div class="code">
1067 <pre>
1068 struct Foo {
1069    size_t  len;
1070 };
1071 </pre>
1072 </div>
1073
1074 <p>
1075 and nothing was known about <tt>size_t</tt>, then accessors would be
1076 written to work with <tt>size_t *</tt>.  Starting in SWIG-1.3.12, this
1077 behavior has been modified.  Specifically, pointers will <em>only</em>
1078 be used if SWIG knows that a datatype corresponds to a structure or
1079 class.  Therefore, the above code would be wrapped into accessors
1080 involving <tt>size_t</tt>.  This change is subtle, but it smooths over
1081 a few problems related to structure wrapping and some of SWIG's
1082 customization features.
1083 </p>
1084
1085 <H2><a name="SWIGPlus_default_args"></a>6.7 Default arguments</H2>
1086
1087
1088 <p>
1089 SWIG will wrap all types of functions that have default arguments. For example member functions:
1090 </p>
1091
1092 <div class="code">
1093 <pre>
1094 class Foo {
1095 public:
1096     void bar(int x, int y = 3, int z = 4);
1097 };
1098 </pre>
1099 </div>
1100
1101 <p>
1102 SWIG handles default arguments by generating an extra overloaded method for each defaulted argument.
1103 SWIG is effectively handling methods with default arguments as if it was wrapping the equivalent overloaded methods.
1104 Thus for the example above, it is as if we had instead given the following to SWIG:
1105 </p>
1106
1107 <div class="code">
1108 <pre>
1109 class Foo {
1110 public:
1111     void bar(int x, int y, int z);
1112     void bar(int x, int y);
1113     void bar(int x);
1114 };
1115 </pre>
1116 </div>
1117
1118 <p>
1119 The wrappers produced are exactly the same as if the above code was instead fed into SWIG.
1120 Details of this are covered later in the <a href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions and Methods</a> section.
1121 This approach allows SWIG to wrap all possible default arguments, but can be verbose.
1122 For example if a method has ten default arguments, then eleven wrapper methods are generated.
1123 </p>
1124
1125 <p>
1126 Please see the <a href="Customization.html#Customization_features_default_args">Features and default arguments</a>
1127 section for more information on using <tt>%feature</tt> with functions with default arguments.
1128 The <a href="#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a> section 
1129 also deals with using <tt>%rename</tt> and <tt>%ignore</tt> on methods with default arguments.
1130 If you are writing your own typemaps for types used in methods with default arguments, you may also need to write a <tt>typecheck</tt> typemap.
1131 See the <a href="Typemaps.html#Typemaps_overloading">Typemaps and overloading</a> section for details or otherwise
1132 use the <tt>compactdefaultargs</tt> feature flag as mentioned below.
1133 </p>
1134
1135 <p>
1136 <b>Compatibility note:</b> Versions of SWIG prior to SWIG-1.3.23 wrapped default arguments slightly differently.
1137 Instead a single wrapper method was generated and the default values were copied into the C++ wrappers
1138 so that the method being wrapped was then called with all the arguments specified.
1139 If the size of the wrappers are a concern then this approach to wrapping methods with default arguments
1140 can be re-activated by using the <tt>compactdefaultargs</tt> 
1141 <a href="Customization.html#Customization_feature_flags">feature flag</a>.
1142 </p>
1143
1144 <div class="code">
1145 <pre>
1146 %feature("compactdefaultargs") Foo::bar;
1147 class Foo {
1148 public:
1149     void bar(int x, int y = 3, int z = 4);
1150 };
1151 </pre>
1152 </div>
1153
1154
1155 <p>
1156 This is great for reducing the size of the wrappers, but the caveat is it does not work for the statically typed languages,
1157 such as C# and Java,
1158 which don't have optional arguments in the language, 
1159 Another restriction of this feature is that it cannot handle default arguments that are not public.
1160 The following example illustrates this:
1161 </p>
1162
1163 <div class="code">
1164 <pre>
1165 class Foo {
1166 private:
1167    static const int spam;
1168 public:
1169    void bar(int x, int y = spam);   // Won't work with %feature("compactdefaultargs") -
1170                                     // private default value
1171 };
1172 </pre>
1173 </div>
1174
1175 <p>
1176 This produces uncompileable wrapper code because default values in C++ are
1177 evaluated in the same scope as the member function whereas SWIG
1178 evaluates them in the scope of a wrapper function (meaning that the
1179 values have to be public). 
1180 </p>
1181
1182 <p>
1183 This feature is automatically turned on when wrapping <a href="SWIG.html#SWIG_default_args">C code with default arguments</a>
1184 and whenever keyword arguments (kwargs) are specified for either C or C++ code.
1185 Keyword arguments are a language feature of some scripting languages, for example Ruby and Python.
1186 SWIG is unable to support kwargs when wrapping overloaded methods, so the default approach cannot be used.
1187 </p>
1188
1189 <H2><a name="SWIGPlus_nn15"></a>6.8 Protection</H2>
1190
1191
1192 <p>
1193  SWIG wraps class members that are public following the C++
1194  conventions, i.e., by explicit public declaration or by the use of
1195  the <tt> using</tt> directive. In general, anything specified in a
1196  private or protected section will be ignored, although the internal
1197  code generator sometimes looks at the contents of the private and
1198  protected sections so that it can properly generate code for default
1199  constructors and destructors. Directors could also modify the way
1200  non-public virtual protected members are treated.
1201 </p>
1202
1203 <p>
1204 By default, members of a class definition are assumed to be private
1205 until you explicitly give a `<tt>public:</tt>' declaration (This is
1206 the same convention used by C++).
1207 </p>
1208
1209 <H2><a name="SWIGPlus_nn16"></a>6.9 Enums and constants</H2>
1210
1211
1212 <p>
1213 Enumerations and constants are handled differently by the different language modules and are described in detail in the appropriate language chapter.
1214 However, many languages map enums and constants in a class definition 
1215 into constants with the classname as a prefix. For example :</p>
1216
1217 <div class="code"><pre>
1218 class Swig {
1219 public:
1220         enum {ALE, LAGER, PORTER, STOUT};
1221 };
1222
1223 </pre></div>
1224 <p>
1225 Generates the following set of constants in the target scripting language :</p>
1226
1227 <div class="targetlang"><pre>
1228 Swig_ALE = Swig::ALE
1229 Swig_LAGER = Swig::LAGER
1230 Swig_PORTER = Swig::PORTER
1231 Swig_STOUT = Swig::STOUT
1232
1233 </pre></div>
1234
1235 <p>
1236 Members declared as <tt>const</tt> are wrapped as read-only members and do not create constants.
1237 </p>
1238
1239 <H2><a name="SWIGPlus_nn17"></a>6.10 Friends</H2>
1240
1241
1242 <p>
1243 Friend declarations are recognised by SWIG. For example, if
1244 you have this code:
1245 </p>
1246
1247 <div class="code">
1248 <pre>
1249 class Foo {
1250 public:
1251      ...
1252      friend void blah(Foo *f);
1253      ...
1254 };
1255 </pre>
1256 </div>
1257
1258 <p>
1259 then the <tt>friend</tt> declaration does result in a wrapper code
1260 equivalent to one generated for the following declaration
1261 </p>
1262
1263 <div class="code">
1264 <pre>
1265 class Foo {
1266 public:
1267     ...
1268 };
1269
1270 void blah(Foo *f);    
1271 </pre>
1272 </div>
1273
1274 <p>
1275 A friend declaration, as in C++, is understood to be in the same scope
1276 where the class is declared, hence, you can have
1277 </p>
1278
1279 <div class="code">
1280 <pre>
1281
1282 %ignore bar::blah(Foo *f);
1283
1284 namespace bar {
1285
1286   class Foo {
1287   public:
1288      ...
1289      friend void blah(Foo *f);
1290      ...
1291   };
1292 }
1293 </pre>
1294 </div>
1295
1296 <p>
1297 and a wrapper for the method 'blah' will not be generated.
1298 </p>
1299
1300 <H2><a name="SWIGPlus_nn18"></a>6.11 References and pointers</H2>
1301
1302
1303 <p>
1304 C++ references are supported, but SWIG transforms them back into pointers. For example,
1305 a declaration like this :</p>
1306
1307 <div class="code"><pre>
1308 class Foo {
1309 public:
1310         double bar(double &amp;a);
1311 }
1312 </pre></div>
1313
1314 <p>
1315 has a low-level accessor
1316 </p>
1317
1318 <div class="code"><pre>
1319 double Foo_bar(Foo *obj, double *a) {
1320         obj-&gt;bar(*a);
1321 }
1322 </pre></div>
1323
1324 <p>
1325 As a special case, most language modules pass <tt>const</tt> references to primitive datatypes (<tt>int</tt>, <tt>short</tt>,
1326 <tt>float</tt>, etc.) by value instead of pointers.  For example, if you have a function like this,
1327 </p>
1328
1329 <div class="code">
1330 <pre>
1331 void foo(const int &amp;x);
1332 </pre>
1333 </div>
1334
1335 <p>
1336 it is called from a script as follows:
1337 </p>
1338
1339 <div class="targetlang">
1340 <pre>
1341 foo(3)              # Notice pass by value
1342 </pre>
1343 </div>
1344
1345 <p>
1346 Functions that return a reference are remapped to return a pointer instead.
1347 For example:
1348 </p>
1349
1350 <div class="code"><pre>
1351 class Bar {
1352 public:
1353      Foo &amp;spam();
1354 };
1355 </pre>
1356 </div>
1357
1358 <p>
1359 Generates an accessor like this:
1360 </p>
1361
1362 <div class="code">
1363 <pre>
1364 Foo *Bar_spam(Bar *obj) {
1365    Foo &amp;result = obj-&gt;spam();
1366    return &amp;result;
1367 }
1368 </pre>
1369 </div>
1370
1371 <p>
1372 However, functions that return <tt>const</tt> references to primitive datatypes (<tt>int</tt>, <tt>short</tt>, etc.) normally
1373 return the result as a value rather than a pointer.  For example, a function like this,
1374 </p>
1375
1376 <div class="code">
1377 <pre>
1378 const int &amp;bar();
1379 </pre>
1380 </div>
1381
1382 <p>
1383 will return integers such as 37 or 42 in the target scripting language rather than a pointer to an integer.
1384 </p>
1385
1386 <P>
1387 Don't return references to objects allocated as local variables on the
1388 stack.  SWIG doesn't make a copy of the objects so this will probably
1389 cause your program to crash.
1390
1391
1392
1393 <p>
1394 <b>Note:</b> The special treatment for references to primitive datatypes is necessary to provide
1395 more seamless integration with more advanced C++ wrapping applications---especially related to 
1396 templates and the STL.  This was first added in SWIG-1.3.12.
1397 </p>
1398
1399
1400 <H2><a name="SWIGPlus_nn19"></a>6.12 Pass and return by value</H2>
1401
1402
1403 <p>
1404 Occasionally, a C++ program will pass and return class objects by value.  For example, a function
1405 like this might appear:
1406 </p>
1407
1408 <div class="code">
1409 <pre>
1410 Vector cross_product(Vector a, Vector b);
1411 </pre>
1412 </div>
1413
1414 <p>
1415 If no information is supplied about <tt>Vector</tt>, SWIG creates a wrapper function similar to the
1416 following:
1417 </p>
1418
1419 <div class="code">
1420 <pre>
1421 Vector *wrap_cross_product(Vector *a, Vector *b) {
1422    Vector x = *a;
1423    Vector y = *b;
1424    Vector r = cross_product(x,y);
1425    return new Vector(r);
1426 }</pre>
1427 </div>
1428
1429 <p>
1430 In order for the wrapper code to compile, <tt>Vector</tt> must define a copy constructor and a 
1431 default constructor.
1432 </p>
1433
1434 <p>
1435 If <tt>Vector</tt> is defined as a class in the interface, but it does not
1436 support a default constructor, SWIG changes the wrapper code by encapsulating
1437 the arguments inside a special C++ template wrapper class, through a process
1438 called the "Fulton Transform".  This produces a wrapper that looks like this:
1439 </p>
1440
1441 <div class="code">
1442 <pre>
1443 Vector cross_product(Vector *a, Vector *b) {
1444    SwigValueWrapper&lt;Vector&gt; x = *a;
1445    SwigValueWrapper&lt;Vector&gt; y = *b;
1446    SwigValueWrapper&lt;Vector&gt; r = cross_product(x,y);
1447    return new Vector(r);
1448 }
1449 </pre>
1450 </div>
1451
1452 <p>
1453 This transformation is a little sneaky, but it provides support for
1454 pass-by-value even when a class does not provide a default constructor
1455 and it makes it possible to properly support a number of SWIG's
1456 customization options.  The definition of <tt>SwigValueWrapper</tt>
1457 can be found by reading the SWIG wrapper code. This class is really nothing more than a thin
1458 wrapper around a pointer. 
1459 </p>
1460
1461 <p>
1462 Although SWIG usually detects the classes to which the Fulton Transform should
1463 be applied, in some situations it's necessary to override it.  That's done with
1464 <tt>%feature("valuewrapper")</tt> to ensure it is used and <tt>%feature("novaluewrapper")</tt>
1465 to ensure it is not used:
1466 </p>
1467
1468 <div class="code"><pre>
1469 %feature("novaluewrapper") A;    
1470 class A;
1471
1472 %feature("valuewrapper") B;
1473 struct B { 
1474     B();
1475     // ....
1476 };   
1477 </pre></div>
1478
1479 <p>
1480 It is well worth considering turning this feature on for classes that do have a default constructor. 
1481 It will remove a redundant constructor call at the point of the variable declaration in the wrapper, 
1482 so will generate notably better performance for large objects or for classes with expensive construction.
1483 Alternatively consider returning a reference or a pointer.
1484 </p>
1485
1486 <p>
1487 <b>Note:</b> this transformation has no effect on typemaps
1488 or any other part of SWIG---it should be transparent except that you
1489 may see this code when reading the SWIG output file.
1490 </p>
1491
1492 <p>
1493 <b>
1494 Note: </b>This template transformation is new in SWIG-1.3.11 and may be refined in
1495 future SWIG releases.  In practice, it is only absolutely necessary to do this for
1496 classes that don't define a default constructor.  
1497 </p>
1498
1499 <p>
1500 <b>Note:</b> The use of this template only occurs when objects are passed or returned by value.
1501 It is not used for C++ pointers or references.
1502 </p>
1503
1504 <H2><a name="SWIGPlus_nn20"></a>6.13 Inheritance</H2>
1505
1506
1507 <p>
1508 SWIG supports C++ inheritance of classes and allows both single and
1509 multiple inheritance, as limited or allowed by the target
1510 language. The SWIG type-checker knows about the relationship between
1511 base and derived classes and allows pointers to any object of a
1512 derived class to be used in functions of a base class. The
1513 type-checker properly casts pointer values and is safe to use with
1514 multiple inheritance.
1515 </p>
1516
1517 <p> SWIG treats private or protected inheritance as close to the C++
1518 spirit, and target language capabilities, as possible. In most
1519 cases, this means that SWIG will parse the non-public inheritance
1520 declarations, but that will have no effect in the generated code,
1521 besides the implicit policies derived for constructor and
1522 destructors. 
1523 </p>
1524
1525
1526 <p>
1527 The following example shows how SWIG handles inheritance. For clarity,
1528 the full C++ code has been omitted.</p>
1529
1530 <div class="code"><pre>
1531 // shapes.i
1532 %module shapes
1533 %{
1534 #include "shapes.h"
1535 %}
1536
1537 class Shape {
1538 public:
1539         double x,y;
1540         virtual double area() = 0;
1541         virtual double perimeter() = 0;
1542         void    set_location(double x, double y);
1543 };
1544 class Circle : public Shape {
1545 public:
1546         Circle(double radius);
1547         ~Circle();
1548         double area();
1549         double perimeter();
1550 };
1551 class Square : public Shape {
1552 public:
1553         Square(double size);
1554         ~Square();
1555         double area();
1556         double perimeter();
1557 }
1558 </pre></div>
1559
1560 <p>
1561 When wrapped into Python, we can perform the following operations (shown using the low level Python accessors):
1562 </p>
1563
1564 <div class="targetlang"><pre>
1565 $ python
1566 &gt;&gt;&gt; import shapes
1567 &gt;&gt;&gt; circle = shapes.new_Circle(7)
1568 &gt;&gt;&gt; square = shapes.new_Square(10)
1569 &gt;&gt;&gt; print shapes.Circle_area(circle)
1570 153.93804004599999757
1571 &gt;&gt;&gt; print shapes.Shape_area(circle)
1572 153.93804004599999757
1573 &gt;&gt;&gt; print shapes.Shape_area(square)
1574 100.00000000000000000
1575 &gt;&gt;&gt; shapes.Shape_set_location(square,2,-3)
1576 &gt;&gt;&gt; print shapes.Shape_perimeter(square)
1577 40.00000000000000000
1578 &gt;&gt;&gt;
1579 </pre></div>
1580
1581 <p>
1582 In this example,  Circle and Square objects have been created.  Member
1583 functions can be invoked on each object by making calls to
1584 <tt>Circle_area</tt>, <tt>Square_area</tt>, and so on. However, the same
1585 results can be accomplished by simply using the <tt>Shape_area</tt>
1586 function on either object.
1587 </p>
1588
1589 <p>
1590 One important point concerning inheritance is that the low-level
1591 accessor functions are only generated for classes in which they are
1592 actually declared.  For instance, in the above example, the method
1593 <tt>set_location()</tt> is only accessible as
1594 <tt>Shape_set_location()</tt> and not as
1595 <tt>Circle_set_location()</tt> or <tt>Square_set_location()</tt>.  Of
1596 course, the <tt>Shape_set_location()</tt> function will accept any
1597 kind of object derived from Shape.  Similarly, accessor functions for
1598 the attributes <tt>x</tt> and <tt>y</tt> are generated as
1599 <tt>Shape_x_get()</tt>, <tt>Shape_x_set()</tt>,
1600 <tt>Shape_y_get()</tt>, and <tt>Shape_y_set()</tt>.  Functions such as
1601 <tt>Circle_x_get()</tt> are not available--instead you should use
1602 <tt>Shape_x_get()</tt>.
1603 </p>
1604
1605 <p>
1606 Note that there is a one to one correlation between the low-level accessor functions and
1607 the proxy methods and therefore there is also a one to one correlation between
1608 the C++ class methods and the generated proxy class methods.
1609 </p>
1610
1611 <p>
1612 <b>Note:</b>  For the best results, SWIG requires all
1613 base classes to be defined in an interface.  Otherwise, you may get a
1614 warning message like this:
1615 </p>
1616
1617 <div class="shell">
1618 <pre>
1619 example.i:18: Warning(401): Nothing known about base class 'Foo'. Ignored.
1620 </pre>
1621 </div>
1622
1623 <p>
1624 If any base class is undefined, SWIG still generates correct type
1625 relationships.  For instance, a function accepting a <tt>Foo *</tt>
1626 will accept any object derived from <tt>Foo</tt> regardless of whether
1627 or not SWIG actually wrapped the <tt>Foo</tt> class.  If you really
1628 don't want to generate wrappers for the base class, but you want to
1629 silence the warning, you might consider using the <tt>%import</tt>
1630 directive to include the file that defines <tt>Foo</tt>.
1631 <tt>%import</tt> simply gathers type information, but doesn't generate
1632 wrappers.  Alternatively, you could just define <tt>Foo</tt> as an empty class
1633 in the SWIG interface or use
1634 <a href="Warnings.html#Warnings_suppression">warning suppression</a>.
1635 </p>
1636
1637 <p>
1638 <b>Note:</b> <tt>typedef</tt>-names <em>can</em> be used as base classes.  For example:
1639 </p>
1640
1641 <div class="code">
1642 <pre>
1643 class Foo {
1644 ...
1645 };
1646
1647 typedef Foo FooObj;
1648 class Bar : public FooObj {     // Ok.  Base class is Foo
1649 ...
1650 };
1651 </pre>
1652 </div>
1653
1654 <p>
1655 Similarly, <tt>typedef</tt> allows unnamed structures to be used as base classes. For example:
1656 </p>
1657
1658 <div class="code">
1659 <pre>
1660 typedef struct {
1661    ...
1662 } Foo;
1663
1664 class Bar : public Foo {    // Ok. 
1665 ...
1666 };
1667 </pre>
1668 </div>
1669
1670 <p>
1671 <b>Compatibility Note:</b> Starting in version 1.3.7, SWIG only
1672 generates low-level accessor wrappers for the declarations that are
1673 actually defined in each class.  This differs from SWIG1.1 which used
1674 to inherit all of the declarations defined in base classes and
1675 regenerate specialized accessor functions such as
1676 <tt>Circle_x_get()</tt>, <tt>Square_x_get()</tt>,
1677 <tt>Circle_set_location()</tt>, and <tt>Square_set_location()</tt>.
1678 This behavior resulted in huge amounts of replicated code for large
1679 class hierarchies and made it awkward to build applications spread
1680 across multiple modules (since accessor functions are duplicated in
1681 every single module).  It is also unnecessary to have such wrappers
1682 when advanced features like proxy classes are used.  
1683
1684 <b>Note:</b> Further optimizations are enabled when using the
1685 <tt>-fvirtual</tt> option, which avoids the regenerating of wrapper
1686 functions for virtual members that are already defined in a base
1687 class.
1688 </p>
1689
1690 <H2><a name="SWIGPlus_nn21"></a>6.14 A brief discussion of multiple inheritance, pointers,  and type checking</H2>
1691
1692
1693 <p>
1694 When a target scripting language refers to a C++ object, it normally
1695 uses a tagged pointer object that contains both the value of the
1696 pointer and a type string.  For example, in Tcl, a C++ pointer might
1697 be encoded as a string like this:
1698 </p>
1699
1700 <div class="diagram">
1701 <pre>
1702 _808fea88_p_Circle
1703 </pre>
1704 </div>
1705
1706 <p>
1707 A somewhat common question is whether or not the type-tag could be safely
1708 removed from the pointer.  For instance, to get better performance, could you
1709 strip all type tags and just use simple integers instead?
1710 </p>
1711
1712 <p>
1713 In general, the answer to this question is no.  In the wrappers, all
1714 pointers are converted into a common data representation in the target
1715 language.  Typically this is the equivalent of casting a pointer to <tt>void *</tt>.
1716 This means that any C++ type information associated with the pointer is
1717 lost in the conversion.
1718 </p>
1719
1720 <p>
1721 The problem with losing type information is that it is needed to
1722 properly support many advanced C++ features--especially multiple
1723 inheritance.  For example, suppose you had code like this:
1724 </p>
1725
1726 <div class="code">
1727 <pre>
1728 class A {
1729 public:
1730    int x;
1731 };
1732
1733 class B {
1734 public:
1735    int y;
1736 };
1737
1738 class C : public A, public B {
1739 };
1740
1741 int A_function(A *a) {
1742    return a-&gt;x;
1743 }
1744
1745 int B_function(B *b) {
1746    return b-&gt;y;
1747 }
1748 </pre>
1749 </div>
1750
1751 <p>
1752 Now, consider the following code that uses <tt>void *</tt>.
1753 </p>
1754
1755 <div class="code">
1756 <pre>
1757 C *c = new C();
1758 void *p = (void *) c;
1759 ...
1760 int x = A_function((A *) p);
1761 int y = B_function((B *) p);
1762 </pre>
1763 </div>
1764
1765 <p>
1766 In this code, both <tt>A_function()</tt> and <tt>B_function()</tt> may
1767 legally accept an object of type <tt>C *</tt> (via inheritance).
1768 However, one of the functions will always return the wrong result when
1769 used as shown. The reason for this is that even though <tt>p</tt>
1770 points to an object of type <tt>C</tt>, the casting operation doesn't
1771 work like you would expect.  Internally, this has to do with the data
1772 representation of <tt>C</tt>. With multiple inheritance, the data from
1773 each base class is stacked together.  For example:
1774 </p>
1775
1776 <div class="diagram">
1777 <pre>
1778              ------------    &lt;--- (C *),  (A *)
1779             |     A      |
1780             |------------|   &lt;--- (B *)
1781             |     B      |
1782              ------------   
1783 </pre>
1784 </div>
1785
1786 <p>
1787 Because of this stacking, a pointer of type <tt>C *</tt> may change
1788 value when it is converted to a <tt>A *</tt> or <tt>B *</tt>.
1789 However, this adjustment does <em>not</em> occur if you are converting from a
1790 <tt>void *</tt>.
1791 </p>
1792
1793 <p>
1794 The use of type tags marks all pointers with the real type of the
1795 underlying object.  This extra information is then used by SWIG
1796 generated wrappers to correctly cast pointer values under inheritance
1797 (avoiding the above problem). 
1798 </p>
1799
1800 <p>
1801 Some of the language modules are able to solve the problem by storing multiple instances of the pointer, for example, <tt>A *</tt>,
1802 in the A proxy class as well as <tt>C *</tt> in the C proxy class. The correct cast can then be made by choosing the correct <tt>void *</tt>
1803 pointer to use and is guaranteed to work as the cast to a void pointer and back to the same type does not lose any type information:
1804 </p>
1805
1806 <div class="code">
1807 <pre>
1808 C *c = new C();
1809 void *p = (void *) c;
1810 void *pA = (void *) c;
1811 void *pB = (void *) c;
1812 ...
1813 int x = A_function((A *) pA);
1814 int y = B_function((B *) pB);
1815 </pre>
1816 </div>
1817
1818 <p>
1819 In practice, the pointer is held as an integral number in the target language proxy class.
1820 </p>
1821
1822 <H2><a name="SWIGPlus_overloaded_methods"></a>6.15 Wrapping Overloaded Functions and Methods</H2>
1823
1824
1825 <p>
1826 In many language modules, SWIG provides partial support for overloaded functions, methods, and
1827 constructors.  For example, if you supply SWIG with overloaded functions like this:
1828 </p>
1829
1830 <div class="code">
1831 <pre>
1832 void foo(int x) {
1833    printf("x is %d\n", x);
1834 }
1835 void foo(char *x) {
1836    printf("x is '%s'\n", x);
1837 }
1838 </pre>
1839 </div>
1840
1841 <p>
1842 The function is used in a completely natural way.  For example:
1843 </p>
1844
1845 <div class="targetlang">
1846 <pre>
1847 &gt;&gt;&gt; foo(3)
1848 x is 3
1849 &gt;&gt;&gt; foo("hello")
1850 x is 'hello'
1851 &gt;&gt;&gt;
1852 </pre>
1853 </div>
1854
1855 <p>
1856 Overloading works in a similar manner for methods and constructors.  For example if you have
1857 this code,
1858 </p>
1859
1860 <div class="code">
1861 <pre>
1862 class Foo {
1863 public:
1864      Foo();
1865      Foo(const Foo &amp;);   // Copy constructor
1866      void bar(int x);
1867      void bar(char *s, int y);
1868 };
1869 </pre>
1870 </div>
1871
1872 <p>
1873 it might be used like this
1874 </p>
1875
1876 <div class="targetlang">
1877 <pre>
1878 &gt;&gt;&gt; f = Foo()          # Create a Foo
1879 &gt;&gt;&gt; f.bar(3)
1880 &gt;&gt;&gt; g = Foo(f)         # Copy Foo
1881 &gt;&gt;&gt; f.bar("hello",2)
1882 </pre>
1883 </div>
1884
1885 <H3><a name="SWIGPlus_nn24"></a>6.15.1 Dispatch function generation</H3>
1886
1887
1888 <p>
1889 The implementation of overloaded functions and methods is somewhat
1890 complicated due to the dynamic nature of scripting languages.  Unlike
1891 C++, which binds overloaded methods at compile time, SWIG must
1892 determine the proper function as a runtime check for scripting language targets. This check is
1893 further complicated by the typeless nature of certain scripting languages. For instance,
1894 in Tcl, all types are simply strings.  Therefore, if you have two overloaded functions
1895 like this,
1896 </p>
1897
1898 <div class="code">
1899 <pre>
1900 void foo(char *x);
1901 void foo(int x);
1902 </pre>
1903 </div>
1904
1905 <p>
1906 the order in which the arguments are checked plays a rather critical role.
1907 </p>
1908
1909 <p>
1910 For statically typed languages, SWIG uses the language's method overloading mechanism.
1911 To implement overloading for the scripting languages, SWIG generates a dispatch function that checks the
1912 number of passed arguments and their types.  To create this function, SWIG
1913 first examines all of the overloaded methods and ranks them according
1914 to the following rules:
1915 </p>
1916
1917 <ol>
1918 <li><b>Number of required arguments.</b> Methods are sorted by increasing number of
1919 required arguments.
1920 </li>
1921 <li><p><b>Argument type precedence.</b>  All C++ datatypes are assigned a numeric type precedence value
1922 (which is determined by the language module).</p>
1923
1924 <div class="diagram">
1925 <pre>
1926 Type              Precedence
1927 ----------------  ----------
1928 TYPE *            0     (High)
1929 void *            20
1930 Integers          40
1931 Floating point    60
1932 char              80
1933 Strings           100   (Low)
1934 </pre>
1935 </div>
1936
1937 <p>
1938 Using these precedence values, overloaded methods with the same number of required arguments are sorted in increased
1939 order of precedence values.
1940 </p>
1941 </li>
1942 </ol>
1943
1944 <p>
1945 This may sound very confusing, but an example will help.  Consider the following collection of
1946 overloaded methods:
1947 </p>
1948
1949 <div class="code">
1950 <pre>
1951 void foo(double);
1952 void foo(int);
1953 void foo(Bar *);
1954 void foo();
1955 void foo(int x, int y, int z, int w);
1956 void foo(int x, int y, int z = 3);
1957 void foo(double x, double y);
1958 void foo(double x, Bar *z);
1959 </pre>
1960 </div>
1961
1962 <p>
1963 The first rule simply ranks the functions by required argument count.
1964 This would produce the following list:
1965 </p>
1966
1967 <div class="diagram">
1968 <pre>
1969 rank
1970 -----
1971 [0]   foo()
1972 [1]   foo(double);
1973 [2]   foo(int);
1974 [3]   foo(Bar *);
1975 [4]   foo(int x, int y, int z = 3);
1976 [5]   foo(double x, double y)
1977 [6]   foo(double x, Bar *z)
1978 [7]   foo(int x, int y, int z, int w);
1979 </pre>
1980 </div>
1981
1982 <p>
1983 The second rule, simply refines the ranking by looking at argument type precedence values.
1984 </p>
1985
1986 <div class="diagram">
1987 <pre>
1988 rank
1989 -----
1990 [0]   foo()
1991 [1]   foo(Bar *);
1992 [2]   foo(int);
1993 [3]   foo(double);
1994 [4]   foo(int x, int y, int z = 3);
1995 [5]   foo(double x, Bar *z)
1996 [6]   foo(double x, double y)
1997 [7]   foo(int x, int y, int z, int w);
1998 </pre>
1999 </div>
2000
2001 <p>
2002 Finally, to generate the dispatch function, the arguments passed to an overloaded method are simply
2003 checked in the same order as they appear in this ranking.
2004 </p>
2005
2006 <p>
2007 If you're still confused, don't worry about it---SWIG is probably doing the right thing.
2008 </p>
2009
2010 <H3><a name="SWIGPlus_nn25"></a>6.15.2 Ambiguity in Overloading</H3>
2011
2012
2013 <p>
2014 Regrettably, SWIG is not able to support every possible use of valid C++ overloading.  Consider
2015 the following example:
2016 </p>
2017
2018 <div class="code">
2019 <pre>
2020 void foo(int x);
2021 void foo(long x);
2022 </pre>
2023 </div>
2024
2025 <p>
2026 In C++, this is perfectly legal.  However, in a scripting language, there is generally only one kind of integer
2027 object.  Therefore, which one of these functions do you pick?   Clearly, there is no way to truly make a distinction 
2028 just by looking at the value of the integer itself (<tt>int</tt> and <tt>long</tt> may even be the same precision).   
2029 Therefore, when SWIG encounters this situation, it may generate a warning message like this for scripting languages:
2030 </p>
2031
2032 <div class="shell">
2033 <pre>
2034 example.i:4: Warning(509): Overloaded foo(long) is shadowed by foo(int) at example.i:3.
2035 </pre>
2036 </div>
2037
2038 <p>
2039 or for statically typed languages like Java:
2040 </p>
2041
2042 <div class="shell">
2043 <pre>
2044 example.i:4: Warning(516): Overloaded method foo(long) ignored. Method foo(int)
2045 at example.i:3 used.
2046 </pre>
2047 </div>
2048
2049 <p>
2050 This means that the second overloaded function will be inaccessible
2051 from a scripting interface or the method won't be wrapped at all. 
2052 This is done as SWIG does not know how to disambiguate it from an earlier method.
2053 </p>
2054
2055 <p>
2056 Ambiguity problems are known to arise in the following situations:
2057 </p>
2058
2059 <ul>
2060 <li>Integer conversions.   Datatypes such as <tt>int</tt>, <tt>long</tt>, and <tt>short</tt> cannot be disambiguated in some languages. Shown above.
2061 </li>
2062
2063 <li>Floating point conversion.  <tt>float</tt> and <tt>double</tt> can not be disambiguated in some languages.
2064 </li>
2065
2066 <li>Pointers and references. For example, <tt>Foo *</tt> and <tt>Foo &amp;</tt>.
2067 </li>
2068
2069 <li>Pointers and arrays.  For example, <tt>Foo *</tt> and <tt>Foo [4]</tt>.
2070 </li>
2071
2072 <li>Pointers and instances.  For example, <tt>Foo</tt> and <tt>Foo *</tt>.  Note: SWIG converts all
2073 instances to pointers.
2074 </li>
2075
2076 <li>Qualifiers.  For example, <tt>const Foo *</tt> and <tt>Foo *</tt>.
2077 </li>
2078
2079 <li>Default vs. non default arguments.   For example, <tt>foo(int a, int b)</tt> and <tt>foo(int a, int b = 3)</tt>.
2080 </li>
2081 </ul>
2082
2083 <p>
2084 When an ambiguity arises, methods are checked in the same order as they appear in the interface file.
2085 Therefore, earlier methods will shadow methods that appear later.  
2086 </p>
2087
2088 <p>
2089 When wrapping an overloaded function, there is a chance that you will get an error message like this:
2090 </p>
2091
2092 <div class="shell">
2093 <pre>
2094 example.i:3: Warning(467): Overloaded foo(int) not supported (no type checking
2095 rule for 'int').
2096 </pre>
2097 </div>
2098
2099 <p>
2100 This error means that the target language module supports overloading,
2101 but for some reason there is no type-checking rule that can be used to
2102 generate a working dispatch function.  The resulting behavior is then
2103 undefined.  You should report this as a bug to the
2104 <a href="http://www.swig.org/bugs.html">SWIG bug tracking database</a>.
2105 </p>
2106
2107 <p>
2108 If you get an error message such as the following,
2109 </p>
2110
2111 <div class="shell">
2112 <pre>
2113 foo.i:6. Overloaded declaration ignored.  Spam::foo(double )
2114 foo.i:5. Previous declaration is Spam::foo(int )
2115 foo.i:7. Overloaded declaration ignored.  Spam::foo(Bar *,Spam *,int )
2116 foo.i:5. Previous declaration is Spam::foo(int )
2117 </pre>
2118 </div>
2119
2120 <p>
2121 it means that the target language module has not yet implemented support for overloaded
2122 functions and methods.  The only way to fix the problem is to read the next section.
2123 </p>
2124
2125 <H3><a name="ambiguity_resolution_renaming"></a>6.15.3 Ambiguity resolution and renaming</H3>
2126
2127
2128 <p>
2129 If an ambiguity in overload resolution occurs or if a module doesn't
2130 allow overloading, there are a few strategies for dealing with the
2131 problem.  First, you can tell SWIG to ignore one of the methods.  This
2132 is easy---simply use the <tt>%ignore</tt> directive.  For example:
2133 </p>
2134
2135 <div class="code">
2136 <pre>
2137 %ignore foo(long);
2138
2139 void foo(int);
2140 void foo(long);       // Ignored.  Oh well.
2141 </pre>
2142 </div>
2143
2144 <p>
2145 The other alternative is to rename one of the methods.  This can be
2146 done using <tt>%rename</tt>.  For example:
2147 </p>
2148
2149 <div class="code">
2150 <pre>
2151 %rename("foo_short") foo(short);
2152 %rename(foo_long) foo(long);
2153
2154 void foo(int);
2155 void foo(short);      // Accessed as foo_short()
2156 void foo(long);       // Accessed as foo_long()
2157 </pre>
2158 </div>
2159
2160 <p>
2161 Note that the quotes around the new name are optional, however,
2162 should the new name be a C/C++ keyword they would be essential in order to avoid a parsing error.
2163 The <tt>%ignore</tt> and <tt>%rename</tt> directives are both rather powerful
2164 in their ability to match declarations.    When used in their simple form, they apply to
2165 both global functions and methods.  For example:
2166 </p>
2167
2168 <div class="code">
2169 <pre>
2170 /* Forward renaming declarations */
2171 %rename(foo_i) foo(int); 
2172 %rename(foo_d) foo(double);
2173 ...
2174 void foo(int);           // Becomes 'foo_i'
2175 void foo(char *c);       // Stays 'foo' (not renamed)
2176
2177 class Spam {
2178 public:
2179    void foo(int);      // Becomes 'foo_i'
2180    void foo(double);   // Becomes 'foo_d'
2181    ...
2182 };
2183 </pre>
2184 </div>
2185
2186 <p>
2187 If you only want the renaming to apply to a certain scope, the C++ scope resolution operator (::) can be used.
2188 For example:
2189 </p>
2190
2191 <div class="code">
2192 <pre>
2193 %rename(foo_i) ::foo(int);      // Only rename foo(int) in the global scope.
2194                                 // (will not rename class members)
2195
2196 %rename(foo_i) Spam::foo(int);  // Only rename foo(int) in class Spam
2197 </pre>
2198 </div>
2199
2200 <p>
2201 When a renaming operator is applied to a class as in <tt>Spam::foo(int)</tt>, it is applied to
2202 that class and all derived classes.   This can be used to apply a consistent renaming across
2203 an entire class hierarchy with only a few declarations.  For example:
2204 </p>
2205
2206 <div class="code">
2207 <pre>
2208 %rename(foo_i) Spam::foo(int);
2209 %rename(foo_d) Spam::foo(double);
2210
2211 class Spam {
2212 public:
2213    virtual void foo(int);      // Renamed to foo_i
2214    virtual void foo(double);   // Renamed to foo_d
2215    ...
2216 };
2217
2218 class Bar : public Spam {
2219 public:
2220    virtual void foo(int);      // Renamed to foo_i
2221    virtual void foo(double);   // Renamed to foo_d
2222 ...
2223 };
2224
2225 class Grok : public Bar {
2226 public:
2227    virtual void foo(int);      // Renamed to foo_i
2228    virtual void foo(double);   // Renamed to foo_d
2229 ...
2230 };
2231 </pre>
2232 </div>
2233
2234 <p>
2235 It is also possible to include <tt>%rename</tt> specifications in the
2236 class definition itself. For example:
2237 </p>
2238
2239 <div class="code">
2240 <pre>
2241 class Spam {
2242    %rename(foo_i) foo(int);
2243    %rename(foo_d) foo(double);
2244 public:
2245    virtual void foo(int);      // Renamed to foo_i
2246    virtual void foo(double);   // Renamed to foo_d
2247    ...
2248 };
2249
2250 class Bar : public Spam {
2251 public:
2252    virtual void foo(int);      // Renamed to foo_i
2253    virtual void foo(double);   // Renamed to foo_d
2254 ...
2255 };
2256 </pre>
2257 </div>
2258
2259 <p>
2260 In this case, the <tt>%rename</tt> directives still get applied across the entire 
2261 inheritance hierarchy, but it's no longer necessary to explicitly specify the
2262 class prefix <tt>Spam::</tt>. 
2263 </p>
2264
2265 <p>
2266 A special form of <tt>%rename</tt> can be used to apply a renaming just to class
2267 members (of all classes):
2268 </p>
2269
2270 <div class="code">
2271 <pre>
2272 %rename(foo_i) *::foo(int);   // Only rename foo(int) if it appears in a class.
2273 </pre>
2274 </div>
2275
2276 <p>
2277 Note: the <tt>*::</tt> syntax is non-standard C++, but the '*' is meant to be a
2278 wildcard that matches any class name (we couldn't think of a better
2279 alternative so if you have a better idea, send email to
2280 the <a href="http://www.swig.org/mail.html">swig-devel mailing list</a>.
2281 </p>
2282
2283 <p>
2284 Although this discussion has primarily focused on <tt>%rename</tt> all of the same rules
2285 also apply to <tt>%ignore</tt>.  For example:
2286 </p>
2287
2288 <div class="code">
2289 <pre>
2290 %ignore foo(double);          // Ignore all foo(double)
2291 %ignore Spam::foo;            // Ignore foo in class Spam
2292 %ignore Spam::foo(double);    // Ignore foo(double) in class Spam
2293 %ignore *::foo(double);       // Ignore foo(double) in all classes
2294 </pre>
2295 </div>
2296
2297 <p>
2298 When applied to a base class, <tt>%ignore</tt> forces all definitions in derived classes
2299 to disappear. For example, <tt>%ignore Spam::foo(double)</tt> will eliminate <tt>foo(double)</tt> in
2300 <tt>Spam</tt> and all classes derived from <tt>Spam</tt>.
2301 </p>
2302
2303 <p>
2304 <b>Notes on %rename and %ignore:</b>
2305 </p>
2306
2307 <ul>
2308 <li><p>Since, the <tt>%rename</tt> declaration is used to declare a renaming in advance, it can be
2309 placed at the start of an interface file.  This makes it possible to apply a consistent name
2310 resolution without having to modify header files. For example:</p>
2311
2312 <div class="code">
2313 <pre>
2314 %module foo
2315
2316 /* Rename these overloaded functions */
2317 %rename(foo_i) foo(int); 
2318 %rename(foo_d) foo(double);
2319
2320 %include "header.h"
2321 </pre>
2322 </div>
2323 </li>
2324
2325 <li><p>The scope qualifier (::) can also be used on simple names.  For example:</p>
2326 <div class="code">
2327 <pre>
2328 %rename(bar) ::foo;       // Rename foo to bar in global scope only
2329 %rename(bar) Spam::foo;   // Rename foo to bar in class Spam only
2330 %rename(bar) *::foo;      // Rename foo in classes only
2331 </pre>
2332 </div>
2333 </li>
2334
2335 <li><p>Name matching tries to find the most specific match that is
2336 defined.  A qualified name such as <tt>Spam::foo</tt> always has
2337 higher precedence than an unqualified name <tt>foo</tt>.
2338 <tt>Spam::foo</tt> has higher precedence than <tt>*::foo</tt> and
2339 <tt>*::foo</tt> has higher precedence than <tt>foo</tt>.  A
2340 parameterized name has higher precedence than an unparameterized name
2341 within the same scope level.  However, an unparameterized name with a
2342 scope qualifier has higher precedence than a parameterized name in
2343 global scope (e.g., a renaming of <tt>Spam::foo</tt> takes precedence
2344 over a renaming of <tt>foo(int)</tt>).</p>
2345 </li>
2346
2347 <li><p>
2348 The order in which <tt>%rename</tt> directives are defined does not matter
2349 as long as they appear before the declarations to be renamed.  Thus, there is no difference
2350 between saying:</p>
2351
2352 <div class="code">
2353 <pre>
2354 %rename(bar) foo;
2355 %rename(foo_i) Spam::foo(int);
2356 %rename(Foo) Spam::foo;
2357 </pre>
2358 </div>
2359
2360 <p>
2361 and this
2362 </p>
2363
2364 <div class="code">
2365 <pre>
2366 %rename(Foo) Spam::foo;
2367 %rename(bar) foo;
2368 %rename(foo_i) Spam::foo(int);
2369 </pre>
2370 </div>
2371
2372 <p>
2373 (the declarations are not stored in a linked list and order has no
2374 importance).  Of course, a repeated <tt>%rename</tt> directive will
2375 change the setting for a previous <tt>%rename</tt> directive if exactly the 
2376 same name, scope,  and parameters are supplied.
2377 </p>
2378 </li>
2379
2380 <li>For multiple inheritance where renaming rules are defined for multiple base classes,
2381 the first renaming rule found on a depth-first traversal of the class hierarchy 
2382 is used.
2383 </li>
2384
2385 <li><p>The name matching rules strictly follow member qualification rules.
2386 For example, if you have a class like this:</p>
2387
2388 <div class="code">
2389 <pre>
2390 class Spam {
2391 public:
2392    ...
2393    void bar() const;
2394    ...
2395 };
2396 </pre>
2397 </div>
2398
2399 <p>
2400 the declaration
2401 </p>
2402
2403 <div class="code">
2404 <pre>
2405 %rename(name) Spam::bar();
2406 </pre>
2407 </div>
2408
2409 <p>
2410 will not apply as there is no unqualified member <tt>bar()</tt>. The following will apply as
2411 the qualifier matches correctly:
2412 </p>
2413
2414 <div class="code">
2415 <pre>
2416 %rename(name) Spam::bar() const;
2417 </pre>
2418 </div>
2419
2420 <p>
2421 An often overlooked C++ feature is that classes can define two different overloaded members
2422 that differ only in their qualifiers, like this:
2423 </p>
2424
2425 <div class="code">
2426 <pre>
2427 class Spam {
2428 public:
2429    ...
2430    void bar();         // Unqualified member
2431    void bar() const;   // Qualified member
2432    ...
2433 };
2434 </pre>
2435 </div>
2436
2437 <p>
2438 %rename can then be used to target each of the overloaded methods individually. 
2439 For example we can give them separate names in the target language:
2440 </p>
2441
2442 <div class="code">
2443 <pre>
2444 %rename(name1) Spam::bar();
2445 %rename(name2) Spam::bar() const;
2446 </pre>
2447 </div>
2448
2449 <p>
2450 Similarly, if you
2451 merely wanted to ignore one of the declarations, use <tt>%ignore</tt>
2452 with the full qualification.  For example, the following directive
2453 would tell SWIG to ignore the <tt>const</tt> version of <tt>bar()</tt>
2454 above:
2455 </p>
2456
2457 <div class="code">
2458 <pre>
2459 %ignore Spam::bar() const;   // Ignore bar() const, but leave other bar() alone
2460 </pre>
2461 </div>
2462
2463 </li>
2464
2465 <li><p>
2466 Currently no resolution is performed in order to match function parameters. This means function parameter types must match exactly.
2467 For example, namespace qualifiers and typedefs will not work. The following usage of typedefs demonstrates this:
2468
2469 <div class="code">
2470 <pre>
2471 typedef int Integer;
2472
2473 %rename(foo_i) foo(int);
2474
2475 class Spam {
2476 public:
2477    void foo(Integer);  // Stays 'foo' (not renamed)
2478 };
2479 class Ham {
2480 public:
2481    void foo(int);      // Renamed to foo_i
2482 };
2483 </pre>
2484 </div>
2485
2486 <li><p>
2487 The name matching rules also use default arguments for finer control when wrapping methods that have default arguments.
2488 Recall that methods with default arguments are wrapped as if the equivalent overloaded methods had been parsed
2489 (<a href="#SWIGPlus_default_args">Default arguments</a> section).
2490 Let's consider the following example class:</p>
2491
2492 <div class="code">
2493 <pre>
2494 class Spam {
2495 public:
2496    ...
2497    void bar(int i=-1, double d=0.0);
2498    ...
2499 };
2500 </pre>
2501 </div>
2502
2503 <p>
2504 The following <tt>%rename</tt> will match exactly and apply to all the target language overloaded methods because the declaration with the default arguments
2505 exactly matches the wrapped method:
2506 </p>
2507
2508 <div class="code">
2509 <pre>
2510 %rename(newbar) Spam::bar(int i=-1, double d=0.0);
2511 </pre>
2512 </div>
2513
2514 <p>
2515 The C++ method can then be called from the target language with the new name no matter how many arguments are specified, for example:
2516 <tt>newbar(2, 2.0)</tt>, <tt>newbar(2)</tt> or <tt>newbar()</tt>.
2517 However, if the <tt>%rename</tt> does not contain the default arguments, it will only apply to the single equivalent target language overloaded method.
2518 So if instead we have:
2519 </p>
2520
2521 <div class="code">
2522 <pre>
2523 %rename(newbar) Spam::bar(int i, double d);
2524 </pre>
2525 </div>
2526
2527 <p>
2528 The C++ method must then be called from the target language with the new name <tt>newbar(2, 2.0)</tt> when both arguments are supplied
2529 or with the original name as <tt>bar(2)</tt> (one argument) or <tt>bar()</tt> (no arguments).
2530 In fact it is possible to use <tt>%rename</tt> on the equivalent overloaded methods, to rename all the equivalent overloaded methods:
2531 </p>
2532
2533 <div class="code">
2534 <pre>
2535 %rename(bar_2args)   Spam::bar(int i, double d);
2536 %rename(bar_1arg)    Spam::bar(int i);
2537 %rename(bar_default) Spam::bar();
2538 </pre>
2539 </div>
2540
2541 <p>
2542 Similarly, the extra overloaded methods can be selectively ignored using <tt>%ignore</tt>.
2543 </p>
2544
2545 <p>
2546 <b>Compatibility note:</b>  The <tt>%rename</tt> directive introduced the default argument matching rules in SWIG-1.3.23 at the same time as the changes
2547 to wrapping methods with default arguments was introduced.
2548 </p>
2549
2550 </li>
2551
2552 </ul>
2553
2554 <H3><a name="SWIGPlus_nn27"></a>6.15.4 Comments on overloading</H3>
2555
2556
2557 <p>
2558 Support for overloaded methods was first added in SWIG-1.3.14.   The implementation
2559 is somewhat unusual when compared to similar tools.  For instance, the order in which
2560 declarations appear is largely irrelevant in SWIG.   Furthermore, SWIG does not rely
2561 upon trial execution or exception handling to figure out which method to invoke. 
2562 </p>
2563
2564 <p>
2565 Internally, the overloading mechanism is completely configurable by the target language
2566 module.  Therefore, the degree of overloading support may vary from language to language. 
2567 As a general rule, statically typed languages like Java are able to provide more support
2568 than dynamically typed languages like Perl, Python, Ruby, and Tcl.
2569 </p>
2570
2571 <H2><a name="SWIGPlus_nn28"></a>6.16 Wrapping overloaded operators</H2>
2572
2573
2574 <p>
2575 C++ overloaded operator declarations can be wrapped. 
2576 For example, consider a class like this:
2577 </p>
2578
2579 <div class="code">
2580 <pre>
2581 class Complex {
2582 private:
2583   double rpart, ipart;
2584 public:
2585   Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
2586   Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
2587   Complex &amp;operator=(const Complex &amp;c) {
2588     rpart = c.rpart;
2589     ipart = c.ipart;
2590     return *this;
2591   }
2592   Complex operator+(const Complex &amp;c) const {
2593     return Complex(rpart+c.rpart, ipart+c.ipart);
2594   }
2595   Complex operator-(const Complex &amp;c) const {
2596     return Complex(rpart-c.rpart, ipart-c.ipart);
2597   }
2598   Complex operator*(const Complex &amp;c) const {
2599     return Complex(rpart*c.rpart - ipart*c.ipart,
2600                    rpart*c.ipart + c.rpart*ipart);
2601   }
2602   Complex operator-() const {
2603     return Complex(-rpart, -ipart);
2604   }
2605   double re() const { return rpart; }
2606   double im() const { return ipart; }
2607 };
2608 </pre>
2609 </div>
2610
2611 <p>
2612 When operator declarations appear, they are handled in
2613 <em>exactly</em> the same manner as regular methods.  However, the
2614 names of these methods are set to strings like "<tt>operator +</tt>"
2615 or "<tt>operator -</tt>".  The problem with these names is that they
2616 are illegal identifiers in most scripting languages.  For instance,
2617 you can't just create a method called "<tt>operator +</tt>" in
2618 Python--there won't be any way to call it.
2619 </p>
2620
2621 <p>
2622 Some language modules already know how to automatically handle certain
2623 operators (mapping them into operators in the target language).
2624 However, the underlying implementation of this is really managed in a
2625 very general way using the <tt>%rename</tt> directive.  For example,
2626 in Python a declaration similar to this is used:
2627 </p>
2628
2629 <div class="code">
2630 <pre>
2631 %rename(__add__) Complex::operator+;
2632 </pre>
2633 </div>
2634
2635 <p>
2636 This binds the + operator to a method called <tt>__add__</tt> (which
2637 is conveniently the same name used to implement the Python + operator). 
2638 Internally, the generated wrapper code for a wrapped operator will look
2639 something like this pseudocode:
2640 </p>
2641
2642 <div class="code">
2643 <pre>
2644 _wrap_Complex___add__(args) {
2645    ... get args ...
2646    obj-&gt;operator+(args);
2647    ...
2648 }
2649 </pre>
2650 </div>
2651
2652 <p>
2653 When used in the target language, it may now be possible to use the overloaded
2654 operator normally. For example:
2655 </p>
2656
2657 <div class="targetlang">
2658 <pre>
2659 &gt;&gt;&gt; a = Complex(3,4)
2660 &gt;&gt;&gt; b = Complex(5,2)
2661 &gt;&gt;&gt; c = a + b           # Invokes __add__ method
2662 </pre>
2663 </div>
2664
2665 <p>
2666 It is important to realize that there is nothing magical happening
2667 here.  The <tt>%rename</tt> directive really only picks a valid method
2668 name.  If you wrote this:
2669 </p>
2670
2671 <div class="code">
2672 <pre>
2673 %rename(add) operator+;
2674 </pre>
2675 </div>
2676
2677 <p>
2678 The resulting scripting interface might work like this:
2679 </p>
2680
2681 <div class="targetlang">
2682 <pre>
2683 a = Complex(3,4)
2684 b = Complex(5,2)
2685 c = a.add(b)      # Call a.operator+(b)
2686 </pre>
2687 </div>
2688
2689 <p>
2690 All of the techniques described to deal with overloaded functions also
2691 apply to operators.  For example:
2692 </p>
2693
2694 <div class="code">
2695 <pre>
2696 %ignore Complex::operator=;             // Ignore = in class Complex
2697 %ignore *::operator=;                   // Ignore = in all classes
2698 %ignore operator=;                      // Ignore = everywhere.
2699
2700 %rename(__sub__) Complex::operator-; 
2701 %rename(__neg__) Complex::operator-();  // Unary - 
2702 </pre>
2703 </div>
2704
2705 <p>
2706 The last part of this example illustrates how multiple definitions of
2707 the <tt>operator-</tt> method might be handled.
2708 </p>
2709
2710 <p>
2711 Handling operators in this manner is mostly straightforward.  However, there are a few subtle
2712 issues to keep in mind:
2713 </p>
2714
2715 <ul>
2716 <li><p>In C++, it is fairly common to define different versions of the operators to account for
2717 different types.  For example, a class might also include a friend function like this:</p>
2718
2719 <div class="code">
2720 <pre>
2721 class Complex {
2722 public:
2723   friend Complex operator+(Complex &amp;, double);
2724 };
2725 Complex operator+(Complex &amp;, double);
2726 </pre>
2727 </div>
2728
2729 <p>
2730 SWIG simply ignores all <tt>friend</tt> declarations.  Furthermore, it
2731 doesn't know how to associate the associated <tt>operator+</tt> with
2732 the class (because it's not a member of the class).
2733 </p>
2734
2735 <p>
2736 It's still possible to make a wrapper for this operator, but you'll
2737 have to handle it like a normal function. For example:
2738 </p>
2739
2740 <div class="code">
2741 <pre>
2742 %rename(add_complex_double) operator+(Complex &amp;, double);
2743 </pre>
2744 </div>
2745 </li>
2746
2747 <li><p>Certain operators are ignored by default. For instance, <tt>new</tt> and <tt>delete</tt> operators
2748 are ignored as well as conversion operators.
2749 </p></li>
2750
2751 <li>The semantics of certain C++ operators may not match those in the target language.
2752 </li>
2753 </ul>
2754
2755 <H2><a name="SWIGPlus_class_extension"></a>6.17 Class extension</H2>
2756
2757
2758 <p>
2759 New methods can be added to a class using the <tt>%extend</tt>
2760 directive. This directive is primarily used in conjunction with proxy
2761 classes to add additional functionality to an existing class. For
2762 example :
2763 </p>
2764
2765 <div class="code"><pre>
2766 %module vector
2767 %{
2768 #include "vector.h"
2769 %}
2770
2771 class Vector {
2772 public:
2773         double x,y,z;
2774         Vector();
2775         ~Vector();
2776         ... bunch of C++ methods ...
2777         %extend {
2778                 char *__str__() {
2779                         static char temp[256];
2780                         sprintf(temp,"[ %g, %g, %g ]", $self-&gt;x,$self-&gt;y,$self-&gt;z);
2781                         return &amp;temp[0];
2782                 }
2783         }
2784 };
2785 </pre></div>
2786
2787 <p>
2788 This code adds a<tt> __str__</tt> method to our class for producing a
2789 string representation of the object. In Python, such a method would
2790 allow us to print the value of an object using the <tt>print</tt>
2791 command.
2792 </p>
2793
2794 <div class="targetlang"><pre>
2795 &gt;&gt;&gt;
2796 &gt;&gt;&gt; v = Vector();
2797 &gt;&gt;&gt; v.x = 3
2798 &gt;&gt;&gt; v.y = 4
2799 &gt;&gt;&gt; v.z = 0
2800 &gt;&gt;&gt; print(v)
2801 [ 3.0, 4.0, 0.0 ]
2802 &gt;&gt;&gt;
2803
2804 </pre></div>
2805
2806 <p>
2807 The C++ 'this' pointer is often needed to access member variables, methods etc.
2808 The <tt>$self</tt> special variable should be used wherever you could use 'this'.
2809 The example above demonstrates this for accessing member variables.
2810 Note that the members dereferenced by <tt>$self</tt> must be public members as the code is ultimately generated
2811 into a global function and so will not have any access to non-public members.
2812 The implicit 'this' pointer that is present in C++ methods is not present in <tt>%extend</tt> methods.
2813 In order to access anything in the extended class or its base class, an explicit 'this' is required.
2814 The following example shows how one could access base class members:
2815 </p>
2816
2817 <div class="code"><pre>
2818 struct Base {
2819   virtual void method(int v) {
2820     ...
2821   }
2822   int value;
2823 };
2824 struct Derived : Base {
2825 };
2826 %extend Derived {
2827   virtual void method(int v) {
2828     $self-&gt;Base::method(v); // akin to this-&gt;Base::method(v);
2829     $self-&gt;value = v;       // akin to this-&gt;value = v;
2830     ...
2831   }
2832 }
2833 </pre></div>
2834
2835 <p>
2836 The<tt> %extend</tt> directive follows all of the same conventions
2837 as its use with C structures. Please refer to the <a href="SWIG.html#SWIG_adding_member_functions">Adding member functions to C structures</a>
2838 section for further details.
2839 </p>
2840
2841 <p>
2842 <b>Compatibility note:</b>  The <tt>%extend</tt> directive is a new
2843 name for the <tt>%addmethods</tt> directive in SWIG1.1.  Since <tt>%addmethods</tt> could
2844 be used to extend a structure with more than just methods, a more suitable
2845 directive name has been chosen.
2846 </p>
2847
2848 <H2><a name="SWIGPlus_nn30"></a>6.18 Templates</H2>
2849
2850
2851 <p>
2852 Template type names may appear anywhere a type
2853 is expected in an interface file.  For example:
2854 </p>
2855
2856 <div class="code">
2857 <pre>
2858 void foo(vector&lt;int&gt; *a, int n);
2859 void bar(list&lt;int,100&gt; *x);
2860 </pre>
2861 </div>
2862
2863 <p>
2864 There are some restrictions on the use of non-type arguments.  Simple literals
2865 are supported, and so are some constant expressions.  However, use of '&lt;'
2866 and '&gt;' within a constant expressions currently is not supported by SWIG
2867 ('&lt;=' and '&gt;=' are though).  For example:
2868 </p>
2869
2870 <div class="code">
2871 <pre>
2872 void bar(list&lt;int,100&gt; *x);                // OK
2873 void bar(list&lt;int,2*50&gt; *x);               // OK
2874 void bar(list&lt;int,(2&gt;1 ? 100 : 50)&gt; *x)    // Not supported
2875 </pre>
2876 </div>
2877
2878 <p>
2879 The type system is smart enough to figure out clever games
2880 you might try to play with <tt>typedef</tt>.  For instance, consider this code:
2881 </p>
2882
2883 <div class="code">
2884 <pre>
2885 typedef int Integer;
2886 void foo(vector&lt;int&gt; *x, vector&lt;Integer&gt; *y);
2887 </pre>
2888 </div>
2889
2890 <p>
2891 In this case, <tt>vector&lt;Integer&gt;</tt> is exactly the same type
2892 as <tt>vector&lt;int&gt;</tt>.  The wrapper for <tt>foo()</tt> will
2893 accept either variant.
2894 </p>
2895
2896 <p>
2897 Starting with SWIG-1.3.7, simple C++ template declarations can also be
2898 wrapped.  SWIG-1.3.12 greatly expands upon the earlier implementation. Before discussing this any further, there are a few things
2899 you need to know about template wrapping.  First, a bare C++ template
2900 does not define any sort of runnable object-code for which SWIG can
2901 normally create a wrapper.  Therefore, in order to wrap a template,
2902 you need to give SWIG information about a particular template
2903 instantiation (e.g., <tt>vector&lt;int&gt;</tt>,
2904 <tt>array&lt;double&gt;</tt>, etc.).  Second, an instantiation name
2905 such as <tt>vector&lt;int&gt;</tt> is generally not a valid identifier
2906 name in most target languages.  Thus, you will need to give the
2907 template instantiation a more suitable name such as <tt>intvector</tt>
2908 when creating a wrapper.
2909 </p>
2910
2911 <p>
2912 To illustrate, consider the following template definition:
2913 </p>
2914
2915 <div class="code"><pre>
2916 template&lt;class T&gt; class List {
2917 private:
2918     T *data;
2919     int nitems;
2920     int maxitems;
2921 public:
2922     List(int max) {
2923       data = new T [max];
2924       nitems = 0;
2925       maxitems = max;
2926     }
2927     ~List() {
2928       delete [] data;
2929     };
2930     void append(T obj) {
2931       if (nitems &lt; maxitems) {
2932         data[nitems++] = obj;
2933       }
2934     }
2935     int length() {
2936       return nitems;
2937     }
2938     T get(int n) {
2939       return data[n];
2940     }
2941 };
2942 </pre></div>
2943
2944 <p>
2945 By itself, this template declaration is useless--SWIG simply ignores it
2946 because it doesn't know how to generate any code until unless a definition of
2947 <tt>T</tt> is provided.
2948 </p>
2949
2950 <p>
2951 One way to create wrappers for a specific template instantiation is to simply
2952 provide an expanded version of the class directly like this:
2953 </p>
2954
2955 <div class="code">
2956 <pre>
2957 %rename(intList) List&lt;int&gt;;       // Rename to a suitable identifier
2958 class List&lt;int&gt; {
2959 private:
2960     int *data;
2961     int nitems;
2962     int maxitems;
2963 public:
2964     List(int max);
2965     ~List();
2966     void append(int obj);
2967     int length();
2968     int get(int n);
2969 };
2970 </pre>
2971 </div>
2972
2973
2974 <p>
2975 The <tt>%rename</tt> directive is needed to give the template class an appropriate identifier
2976 name in the target language (most languages would not recognize C++ template syntax as a valid
2977 class name).  The rest of the code is the same as what would appear in a normal
2978 class definition.
2979 </p>
2980
2981 <p>
2982 Since manual expansion of templates gets old in a hurry, the <tt>%template</tt> directive can
2983 be used to create instantiations of a template class.  Semantically, <tt>%template</tt> is
2984 simply a shortcut---it expands template code in exactly the same way as shown above.  Here
2985 are some examples:
2986 </p>
2987
2988 <div class="code">
2989 <pre>
2990 /* Instantiate a few different versions of the template */
2991 %template(intList) List&lt;int&gt;;
2992 %template(doubleList) List&lt;double&gt;;
2993 </pre>
2994 </div>
2995
2996 <p>
2997 The argument to <tt>%template()</tt> is the name of the instantiation
2998 in the target language.  The name you choose should not conflict with
2999 any other declarations in the interface file with one exception---it
3000 is okay for the template name to match that of a typedef declaration.
3001 For example:
3002 </p>
3003
3004 <div class="code">
3005 <pre>
3006 %template(intList) List&lt;int&gt;;
3007 ...
3008 typedef List&lt;int&gt; intList;    // OK
3009 </pre>
3010 </div>
3011
3012 <p>
3013 SWIG can also generate wrappers for function templates using a similar technique.
3014 For example:
3015 </p>
3016
3017 <div class="code">
3018 <pre>
3019 // Function template
3020 template&lt;class T&gt; T max(T a, T b) { return a &gt; b ? a : b; }
3021
3022 // Make some different versions of this function
3023 %template(maxint) max&lt;int&gt;;
3024 %template(maxdouble) max&lt;double&gt;;
3025 </pre>
3026 </div>
3027
3028 <p>
3029 In this case, <tt>maxint</tt> and <tt>maxdouble</tt> become unique names for specific 
3030 instantiations of the function.
3031 </p>
3032
3033 <p>
3034 The number of arguments supplied to <tt>%template</tt> should match that in the
3035 original template definition.  Template default arguments are supported.  For example:
3036 </p>
3037
3038 <div class="code">
3039 <pre>
3040 template vector&lt;typename T, int max=100&gt; class vector {
3041 ...
3042 };
3043
3044 %template(intvec) vector&lt;int&gt;;           // OK
3045 %template(vec1000) vector&lt;int,1000&gt;;     // OK
3046 </pre>
3047 </div>
3048
3049 <p>
3050 The <tt>%template</tt> directive should not be used to wrap the same
3051 template instantiation more than once in the same scope.  This will
3052 generate an error.  For example:
3053 </p>
3054
3055 <div class="code">
3056 <pre>
3057 %template(intList) List&lt;int&gt;;
3058 %template(Listint) List&lt;int&gt;;    // Error.   Template already wrapped.
3059 </pre>
3060 </div>
3061
3062 <p>
3063 This error is caused because the template expansion results in two
3064 identical classes with the same name.  This generates a symbol table
3065 conflict.  Besides, it probably more efficient to only wrap a specific
3066 instantiation only once in order to reduce the potential for code
3067 bloat.
3068 </p>
3069
3070 <p>
3071 Since the type system knows how to handle <tt>typedef</tt>, it is
3072 generally not necessary to instantiate different versions of a template
3073 for typenames that are equivalent.  For instance, consider this code:
3074 </p>
3075
3076 <div class="code">
3077 <pre>
3078 %template(intList) vector&lt;int&gt;;
3079 typedef int Integer;
3080 ...
3081 void foo(vector&lt;Integer&gt; *x);
3082 </pre>
3083 </div>
3084
3085 <p>
3086 In this case, <tt>vector&lt;Integer&gt;</tt> is exactly the same type as
3087 <tt>vector&lt;int&gt;</tt>.  Any use of <tt>Vector&lt;Integer&gt;</tt> is mapped back to the 
3088 instantiation of <tt>vector&lt;int&gt;</tt> created earlier.  Therefore, it is
3089 not necessary to instantiate a new class for the type <tt>Integer</tt> (doing so is
3090 redundant and will simply result in code bloat).
3091 </p>
3092
3093 <p>
3094 When a template is instantiated using <tt>%template</tt>, information
3095 about that class is saved by SWIG and used elsewhere in the program.
3096 For example, if you wrote code like this,
3097 </p>
3098
3099 <div class="code">
3100 <pre>
3101 ...
3102 %template(intList) List&lt;int&gt;;
3103 ...
3104 class UltraList : public List&lt;int&gt; {
3105    ...
3106 };
3107 </pre>
3108 </div>
3109
3110 <p>
3111 then SWIG knows that <tt>List&lt;int&gt;</tt> was already wrapped as a class called 
3112 <tt>intList</tt> and arranges to handle the inheritance correctly.    If, on the other hand,
3113 nothing is known about <tt>List&lt;int&gt;</tt>, you will get a warning message similar to this:
3114 </p>
3115
3116 <div class="shell">
3117 <pre>
3118 example.h:42. Nothing known about class 'List&lt;int &gt;' (ignored). 
3119 example.h:42. Maybe you forgot to instantiate 'List&lt;int &gt;' using %template. 
3120 </pre>
3121 </div>
3122
3123 <p>
3124 If a template class inherits from another template class, you need to
3125 make sure that base classes are instantiated before derived classes.
3126 For example:
3127 </p>
3128
3129 <div class="code">
3130 <pre>
3131 template&lt;class T&gt; class Foo {
3132 ...
3133 };
3134
3135 template&lt;class T&gt; class Bar : public Foo&lt;T&gt; {
3136 ...
3137 };
3138
3139 // Instantiate base classes first 
3140 %template(intFoo) Foo&lt;int&gt;;
3141 %template(doubleFoo) Foo&lt;double&gt;;
3142
3143 // Now instantiate derived classes
3144 %template(intBar) Bar&lt;int&gt;;
3145 %template(doubleBar) Bar&lt;double&gt;;
3146 </pre>
3147 </div>
3148
3149 <p>
3150 The order is important since SWIG uses the instantiation names to
3151 properly set up the inheritance hierarchy in the resulting wrapper
3152 code (and base classes need to be wrapped before derived classes).
3153 Don't worry--if you get the order wrong, SWIG should generate a warning message.
3154 </p>
3155
3156 <p>
3157 Occasionally, you may need to tell SWIG about base classes that are defined by templates,
3158 but which aren't supposed to be wrapped.  Since SWIG is not able to automatically
3159 instantiate templates for this purpose, you must do it manually.  To do this, simply
3160 use <tt>%template</tt> with no name.  For example:
3161 </p>
3162
3163 <div class="code">
3164 <pre>
3165 // Instantiate traits&lt;double,double&gt;, but don't wrap it.
3166 %template() traits&lt;double,double&gt;;
3167 </pre>
3168 </div>
3169
3170 <p>
3171 If you have to instantiate a lot of different classes for many different types,
3172 you might consider writing a SWIG macro.  For example:
3173 </p>
3174
3175 <div class="code">
3176 <pre>
3177 %define TEMPLATE_WRAP(prefix, T...) 
3178 %template(prefix ## Foo) Foo&lt;T &gt;;
3179 %template(prefix ## Bar) Bar&lt;T &gt;;
3180 ...
3181 %enddef
3182
3183 TEMPLATE_WRAP(int, int)
3184 TEMPLATE_WRAP(double, double)
3185 TEMPLATE_WRAP(String, char *)
3186 TEMPLATE_WRAP(PairStringInt, std::pair&lt;string, int&gt;)
3187 ...
3188 </pre>
3189 </div>
3190
3191 <p>
3192 Note the use of a vararg macro for the type T. If this wasn't used, the comma in the templated type in the last example would not be possible.
3193 </p>
3194
3195 <p>
3196 The SWIG template mechanism <em>does</em> support specialization. For instance, if you define
3197 a class like this,
3198 </p>
3199
3200 <div class="code">
3201 <pre>
3202 template&lt;&gt; class List&lt;int&gt; {
3203 private:
3204     int *data;
3205     int nitems;
3206     int maxitems;
3207 public:
3208     List(int max);
3209     ~List();
3210     void append(int obj);
3211     int length();
3212     int get(int n);
3213 };
3214 </pre>
3215 </div>
3216
3217 <p>
3218 then SWIG will use this code whenever the user expands <tt>List&lt;int&gt;</tt>.   In practice,
3219 this may have very little effect on the underlying wrapper code since
3220 specialization is often used to provide slightly modified method bodies (which
3221 are ignored by SWIG).  However, special SWIG
3222 directives such as <tt>%typemap</tt>, <tt>%extend</tt>, and so forth can be attached
3223 to a specialization to provide customization for specific types.
3224 </p>
3225
3226 <p>
3227 Partial template specialization is partially supported by SWIG.   For example, this
3228 code defines a template that is applied when the template argument is a pointer.
3229 </p>
3230
3231 <div class="code">
3232 <pre>
3233 template&lt;class T&gt; class List&lt;T*&gt; {
3234 private:
3235     T *data;
3236     int nitems;
3237     int maxitems;
3238 public:
3239     List(int max);
3240     ~List();
3241     void append(int obj);
3242     int length();
3243     T get(int n);
3244 };
3245 </pre>
3246 </div>
3247
3248 <p>
3249 SWIG should be able to handle most simple uses of partial specialization.  However, it may fail
3250 to match templates properly in more complicated cases.  For example, if you have this code,
3251 </p>
3252
3253 <div class="code">
3254 <pre>
3255 template&lt;class T1, class T2&gt; class Foo&lt;T1, T2 *&gt; { };
3256 </pre>
3257 </div>
3258
3259 <p>
3260 SWIG isn't able to match it properly for instantiations like <tt>Foo&lt;int *, int *&gt;</tt>.
3261 This problem is not due to parsing, but due to the fact that SWIG does not currently implement all
3262 of the C++ argument deduction rules.
3263 </p>
3264
3265 <p>
3266 Member function templates are supported.  The underlying principle is the same
3267 as for normal templates--SWIG can't create a wrapper unless you provide
3268 more information about types.  For example, a class with a member template might
3269 look like this:
3270 </p>
3271
3272 <div class="code">
3273 <pre>
3274 class Foo {
3275 public:
3276      template&lt;class T&gt; void bar(T x, T y) { ... };
3277      ...
3278 };
3279 </pre>
3280 </div>
3281
3282 <p>
3283 To expand the template, simply use <tt>%template</tt> inside the class.
3284 </p>
3285
3286 <div class="code">
3287 <pre>
3288 class Foo {
3289 public:
3290      template&lt;class T&gt; void bar(T x, T y) { ... };
3291      ...
3292      %template(barint)    bar&lt;int&gt;;
3293      %template(bardouble) bar&lt;double&gt;;
3294 };
3295 </pre>
3296 </div>
3297
3298 <p>
3299 Or, if you want to leave the original class definition alone, just do this:
3300 </p>
3301
3302 <div class="code">
3303 <pre>
3304 class Foo {
3305 public:
3306      template&lt;class T&gt; void bar(T x, T y) { ... };
3307      ...
3308 };
3309 ...
3310 %extend Foo {
3311      %template(barint)    bar&lt;int&gt;;
3312      %template(bardouble) bar&lt;double&gt;;
3313 };
3314 </pre>
3315 </div>
3316
3317 <p>
3318 or simply
3319 </p>
3320
3321 <div class="code">
3322 <pre>
3323 class Foo {
3324 public:
3325      template&lt;class T&gt; void bar(T x, T y) { ... };
3326      ...
3327 };
3328 ...
3329
3330 %template(bari) Foo::bar&lt;int&gt;;
3331 %template(bard) Foo::bar&lt;double&gt;;
3332 </pre>
3333 </div>
3334
3335 <p>
3336 In this case, the <tt>%extend</tt> directive is not needed, and
3337 <tt>%template</tt> does the exactly same job, i.e., it adds two new
3338 methods to the Foo class. 
3339 </p>
3340
3341
3342 <p>
3343 Note: because of the way that templates are handled, the <tt>%template</tt> directive
3344 must always appear <em>after</em> the definition of the template to be expanded.
3345 </p>
3346
3347 <p>
3348 Now, if your target language supports overloading, you can even try
3349 </p>
3350
3351 <div class="code">
3352 <pre>
3353 %template(bar) Foo::bar&lt;int&gt;;
3354 %template(bar) Foo::bar&lt;double&gt;;
3355 </pre>
3356 </div>
3357
3358 <p>
3359 and since the two new wrapped methods have the same name 'bar', they will be
3360 overloaded, and when called, the correct method will be dispatched
3361 depending on the argument type.
3362 </p>
3363
3364
3365 <p>
3366 When used with members, the <tt>%template</tt> directive may be placed in another
3367 template class.  Here is a slightly perverse example:
3368 </p>
3369
3370 <div class="code">
3371 <pre>
3372 // A template
3373 template&lt;class T&gt; class Foo {
3374 public:
3375      // A member template
3376      template&lt;class S&gt; T bar(S x, S y) { ... };
3377      ...
3378 };
3379
3380 // Expand a few member templates
3381 %extend Foo {
3382   %template(bari) bar&lt;int&gt;;
3383   %template(bard) bar&lt;double&gt;;
3384 }
3385
3386 // Create some wrappers for the template
3387 %template(Fooi) Foo&lt;int&gt;;
3388 %template(Food) Foo&lt;double&gt;;
3389 </pre>
3390 </div>
3391
3392 <p>
3393 Miraculously, you will find that each expansion of <tt>Foo</tt> has member
3394 functions <tt>bari()</tt> and <tt>bard()</tt> added.
3395 </p>
3396
3397 <p>
3398 A common use of member templates is to define constructors for copies
3399 and conversions. For example:
3400 </p>
3401
3402 <div class="code">
3403 <pre>
3404 template&lt;class T1, class T2&gt; struct pair {
3405    T1 first;
3406    T2 second;
3407    pair() : first(T1()), second(T2()) { }
3408    pair(const T1 &amp;x, const T2 &amp;y) : first(x), second(y) { }
3409    template&lt;class U1, class U2&gt; pair(const pair&lt;U1,U2&gt; &amp;x) 
3410                                         : first(x.first),second(x.second) { }
3411 };
3412 </pre>
3413 </div>
3414
3415 <p>
3416 This declaration is perfectly acceptable to SWIG, but the constructor template will be ignored
3417 unless you explicitly expand it.  To do that, you could expand a few versions of the constructor
3418 in the template class itself.  For example:
3419 </p>
3420
3421 <div class="code">
3422 <pre>
3423 %extend pair {
3424    %template(pair) pair&lt;T1,T2&gt;;        // Generate default copy constructor
3425 };
3426 </pre>
3427 </div>
3428
3429 <p>
3430 When using <tt>%extend</tt> in this manner, notice how you can still use the template parameters in
3431 the original template definition. 
3432 </p>
3433
3434 <p>
3435 Alternatively, you could expand the constructor template in selected instantiations. For example:
3436 </p>
3437
3438 <div class="code">
3439 <pre>
3440 // Instantiate a few versions
3441 %template(pairii) pair&lt;int,int&gt;;
3442 %template(pairdd) pair&lt;double,double&gt;;
3443
3444 // Create a default constructor only 
3445 %extend pair&lt;int,int&gt; {
3446    %template(paird) pair&lt;int,int&gt;;         // Default constructor
3447 };
3448
3449 // Create default and conversion constructors 
3450 %extend pair&lt;double,double&gt; {
3451    %template(paird) pair&lt;double,dobule&gt;;   // Default constructor
3452    %template(pairc) pair&lt;int,int&gt;;         // Conversion constructor
3453 };
3454 </pre>
3455 </div>
3456
3457
3458 <p>And if your target language supports overloading, then you can try
3459 instead:
3460 </p>
3461
3462 <div class="code">
3463 <pre>
3464 // Create default and conversion constructors 
3465 %extend pair&lt;double,double&gt; {
3466    %template(pair) pair&lt;double,dobule&gt;;   // Default constructor
3467    %template(pair) pair&lt;int,int&gt;;         // Conversion constructor
3468 };
3469 </pre>
3470 </div>
3471
3472 <p>
3473 In this case, the default and conversion constructors have the same
3474 name. Hence, Swig will overload them and define an unique visible
3475 constructor, that will dispatch the proper call depending on the argument
3476 type.
3477 </p>
3478
3479 <p>
3480 If all of this isn't quite enough and you really want to make
3481 someone's head explode, SWIG directives such as
3482 <tt>%rename</tt>, <tt>%extend</tt>, and <tt>%typemap</tt> can be
3483 included directly in template definitions.  For example:
3484 </p>
3485
3486 <div class="code"><pre>
3487 // File : list.h
3488 template&lt;class T&gt; class List {
3489    ...
3490 public:
3491     %rename(__getitem__) get(int);
3492     List(int max);
3493     ~List();
3494     ...
3495     T get(int index);
3496     %extend {
3497         char *__str__() {
3498             /* Make a string representation */
3499             ...
3500         }
3501     }
3502 };
3503 </pre></div>
3504
3505 <p>
3506 In this example, the extra SWIG directives are propagated to <em>every</em> template 
3507 instantiation.  
3508 </p>
3509
3510 <p>
3511 It is also possible to separate these declarations from the template class.  For example:
3512 </p>
3513
3514 <div class="code">
3515 <pre>
3516 %rename(__getitem__) List::get;
3517 %extend List {
3518     char *__str__() {
3519         /* Make a string representation */
3520         ...
3521     }
3522     /* Make a copy */
3523     T *__copy__() {
3524        return new List&lt;T&gt;(*$self);
3525     }
3526 };
3527
3528 ...
3529 template&lt;class T&gt; class List {
3530     ...
3531     public:
3532     List() { };
3533     T get(int index);
3534     ...
3535 };
3536 </pre>
3537 </div>
3538
3539 <p>
3540 When <tt>%extend</tt> is decoupled from the class definition, it is
3541 legal to use the same template parameters as provided in the class definition.
3542 These are replaced when the template is expanded.
3543 In addition, the <tt>%extend</tt> directive can be used to add
3544 additional methods to a specific instantiation. For example:
3545 </p>
3546
3547 <div class="code">
3548 <pre>
3549 %template(intList) List&lt;int&gt;;
3550
3551 %extend List&lt;int&gt; {
3552     void blah() {
3553           printf("Hey, I'm an List&lt;int&gt;!\n");
3554     }
3555 };
3556 </pre>
3557 </div>
3558
3559 <p>
3560 SWIG even supports overloaded templated functions.  As usual the <tt>%template</tt> directive
3561 is used to wrap templated functions. For example:
3562 </p>
3563
3564 <div class="code">
3565 <pre>
3566 template&lt;class T&gt; void foo(T x) { };
3567 template&lt;class T&gt; void foo(T x, T y) { };
3568
3569 %template(foo) foo&lt;int&gt;;
3570 </pre>
3571 </div>
3572
3573 <p>
3574 This will generate two overloaded wrapper methods, the first will take a single integer as an argument
3575 and the second will take two integer arguments.
3576 </p>
3577
3578 <p>
3579 Needless to say, SWIG's template support provides plenty of
3580 opportunities to break the universe.  That said, an important final
3581 point is that <b>SWIG does not perform extensive error checking of
3582 templates!</b> Specifically, SWIG does not perform type checking nor
3583 does it check to see if the actual contents of the template
3584 declaration make any sense.  Since the C++ compiler will hopefully
3585 check this when it compiles the resulting wrapper file, there is no
3586 practical reason for SWIG to duplicate this functionality (besides,
3587 none of the SWIG developers are masochistic enough to want to
3588 implement this right now).
3589 </p>
3590
3591 <p>
3592 <b>Compatibility Note</b>:  The first implementation of template support relied heavily on
3593 macro expansion in the preprocessor.  Templates have been more tightly integrated into 
3594 the parser and type system in SWIG-1.3.12 and the preprocessor is no longer used. Code
3595 that relied on preprocessing features in template expansion will no longer work.  However,
3596 SWIG still allows the # operator to be used to generate a string from a template argument.
3597 </p>
3598
3599 <p>
3600 <b>Compatibility Note</b>: In earlier versions of SWIG, the <tt>%template</tt> directive
3601 introduced a new class name.  This name could then be used with other directives.  For example:
3602 </p>
3603
3604 <div class="code">
3605 <pre>
3606 %template(vectori) vector&lt;int&gt;;
3607 %extend vectori {
3608     void somemethod() { }
3609 };
3610 </pre>
3611 </div>
3612
3613 <p>
3614 This behavior is no longer supported.  Instead, you should use the original template name
3615 as the class name.  For example:
3616 </p>
3617
3618 <div class="code">
3619 <pre>
3620 %template(vectori) vector&lt;int&gt;;
3621 %extend vector&lt;int&gt; {
3622     void somemethod() { }
3623 };
3624 </pre>
3625 </div>
3626
3627 <p>
3628 Similar changes apply to typemaps and other customization features.
3629 </p>
3630
3631 <H2><a name="SWIGPlus_nn31"></a>6.19 Namespaces</H2>
3632
3633
3634 <p>
3635 Support for C++ namespaces is a relatively late addition to SWIG,
3636 first appearing in SWIG-1.3.12.  Before describing the implementation,
3637 it is worth noting that the semantics of C++ namespaces is extremely
3638 non-trivial--especially with regard to the C++ type system and class
3639 machinery.  At a most basic level, namespaces are sometimes used to 
3640 encapsulate common functionality.  For example:
3641 </p>
3642
3643 <div class="code">
3644 <pre>
3645 namespace math {
3646    double sin(double);
3647    double cos(double);
3648
3649    class Complex {
3650       double im,re;
3651    public:
3652       ...
3653    };
3654    ...
3655 };
3656 </pre>
3657 </div>
3658
3659 <p>
3660 Members of the namespace are accessed in C++ by prepending the namespace prefix
3661 to names. For example:
3662 </p>
3663
3664 <div class="code">
3665 <pre>
3666 double x = math::sin(1.0);
3667 double magnitude(math::Complex *c);
3668 math::Complex c;
3669 ...
3670 </pre>
3671 </div>
3672
3673 <p>
3674 At this level, namespaces are relatively easy to manage.  However, things start to get 
3675 very ugly when you throw in the other ways a namespace can be used.  For example,
3676 selective symbols can be exported from a namespace with <tt>using</tt>.
3677 </p>
3678
3679 <div class="code">
3680 <pre>
3681 using math::Complex;
3682 double magnitude(Complex *c);       // Namespace prefix stripped
3683 </pre>
3684 </div>
3685
3686 <p>
3687 Similarly, the contents of an entire namespace can be made available like this:
3688 </p>
3689
3690 <div class="code">
3691 <pre>
3692 using namespace math;
3693 double x = sin(1.0);
3694 double magnitude(Complex *c);
3695 </pre>
3696 </div>
3697
3698 <p>
3699 Alternatively, a namespace can be aliased:
3700 </p>
3701
3702 <div class="code">
3703 <pre>
3704 namespace M = math;
3705 double x = M::sin(1.0);
3706 double magnitude(M::Complex *c);
3707 </pre>
3708 </div>
3709
3710 <p>
3711 Using combinations of these features, it is possible to write head-exploding code like this:
3712 </p>
3713
3714 <div class="code">
3715 <pre>
3716 namespace A {
3717   class Foo {
3718   };
3719 }
3720
3721 namespace B {
3722    namespace C {
3723       using namespace A;
3724    }
3725    typedef C::Foo FooClass;
3726 }
3727
3728 namespace BIGB = B;
3729
3730 namespace D {
3731    using BIGB::FooClass;
3732    class Bar : public FooClass {
3733    }
3734 };
3735
3736 class Spam : public D::Bar {
3737 };
3738
3739 void evil(A::Foo *a, B::FooClass *b, B::C::Foo *c, BIGB::FooClass *d,
3740           BIGB::C::Foo *e, D::FooClass *f);
3741
3742 </pre>
3743 </div>
3744
3745 <p>
3746 Given the possibility for such perversion, it's hard to imagine how
3747 every C++ programmer might want such code wrapped into the target
3748 language.  Clearly this code defines three different classes.  However, one
3749 of those classes is accessible under at least six different names!
3750 </p>
3751
3752 <p>
3753 SWIG fully supports C++ namespaces in its internal type system and
3754 class handling code.  If you feed SWIG the above code, it will be
3755 parsed correctly, it will generate compilable wrapper code, and it
3756 will produce a working scripting language module.  However, the
3757 default wrapping behavior is to flatten namespaces in the target
3758 language.  This means that the contents of all namespaces are merged
3759 together in the resulting scripting language module.  For example, if
3760 you have code like this,
3761 </p>
3762
3763 <div class="code">
3764 <pre>
3765 %module foo
3766 namespace foo {
3767    void bar(int);
3768    void spam();
3769 }
3770
3771 namespace bar {
3772    void blah();
3773 }
3774
3775 </pre>
3776 </div>
3777
3778 <p>
3779 then SWIG simply creates three wrapper functions <tt>bar()</tt>,
3780 <tt>spam()</tt>, and <tt>blah()</tt> in the target language.  SWIG
3781 does not prepend the names with a namespace prefix nor are the
3782 functions packaged in any kind of nested scope.
3783 </p>
3784
3785 <p>
3786 There is some rationale for taking this approach.  Since C++
3787 namespaces are often used to define modules in C++, there is a natural
3788 correlation between the likely contents of a SWIG module and the contents of
3789 a namespace.  For instance, it would not be unreasonable to assume
3790 that a programmer might make a separate extension module for each C++
3791 namespace.  In this case, it would be redundant to prepend everything
3792 with an additional namespace prefix when the module itself already
3793 serves as a namespace in the target language.   Or put another way, if 
3794 you want SWIG to keep namespaces separate, simply wrap each namespace with its
3795 own SWIG interface.
3796 </p>
3797
3798 <p>
3799 Because namespaces are flattened, it is possible for symbols defined in different
3800 namespaces to generate a name conflict in the target language. For example:
3801 </p>
3802
3803 <div class="code">
3804 <pre>
3805 namespace A {
3806    void foo(int);
3807 }
3808 namespace B {
3809    void foo(double);
3810 }
3811 </pre>
3812 </div>
3813
3814 <p>
3815 When this conflict occurs, you will get an error message that resembles this:
3816 </p>
3817
3818 <div class="shell">
3819 <pre>
3820 example.i:26. Error. 'foo' is multiply defined in the generated module.
3821 example.i:23. Previous declaration of 'foo'
3822 </pre>
3823 </div>
3824
3825 <p>
3826 To resolve this error, simply use <tt>%rename</tt> to disambiguate the declarations.  For example:
3827 </p>
3828
3829 <div class="code">
3830 <pre>
3831 %rename(B_foo) B::foo;
3832 ...
3833 namespace A {
3834    void foo(int);
3835 }
3836 namespace B {
3837    void foo(double);     // Gets renamed to B_foo
3838 }
3839 </pre>
3840 </div>
3841
3842 <p>
3843 Similarly, <tt>%ignore</tt> can be used to ignore declarations.
3844 </p>
3845
3846 <p>
3847 <tt>using</tt> declarations do not have any effect on the generated wrapper
3848 code. They are ignored by SWIG language modules and they do not result in any
3849 code.  However, these declarations <em>are</em> used by the internal type
3850 system to track type-names. Therefore, if you have code like this:
3851 </p>
3852
3853 <div class="code">
3854 <pre>
3855 namespace A {
3856    typedef int Integer;
3857 }
3858 using namespace A;
3859 void foo(Integer x);
3860 </pre>
3861 </div>
3862
3863 <p>
3864 SWIG knows that <tt>Integer</tt> is the same as <tt>A::Integer</tt> which
3865 is the same as <tt>int</tt>.  
3866 </p>
3867
3868 <P>
3869 Namespaces may be combined with templates.  If necessary, the
3870 <tt>%template</tt> directive can be used to expand a template defined
3871 in a different namespace.  For example:
3872 </p>
3873
3874 <div class="code">
3875 <pre>
3876 namespace foo {
3877     template&lt;typename T&gt; T max(T a, T b) { return a &gt; b ? a : b; }
3878 }
3879
3880 using foo::max;
3881
3882 %template(maxint)   max&lt;int&gt;;           // Okay.
3883 %template(maxfloat) foo::max&lt;float&gt;;    // Okay (qualified name).
3884
3885 namespace bar {
3886     using namespace foo;
3887     %template(maxdouble)  max&lt;double&gt;;    // Okay.
3888 }
3889 </pre>
3890 </div>
3891
3892 <p>
3893 The combination of namespaces and other SWIG directives may introduce subtle scope-related problems. 
3894 The key thing to keep in mind is that all SWIG generated wrappers are produced
3895 in the <em>global</em> namespace.   Symbols from other namespaces are always accessed using fully
3896 qualified names---names are never imported into the global space unless the interface happens to
3897 do so with a <tt>using</tt> declaration.  In almost all cases, SWIG adjusts typenames and symbols
3898 to be fully qualified.  However, this is not done in code fragments such as function bodies,
3899 typemaps, exception handlers, and so forth.  For example, consider the following:
3900 </p>
3901
3902 <div class="code">
3903 <pre>
3904 namespace foo {
3905     typedef int Integer;
3906     class bar {
3907     public:
3908        ...
3909     };
3910 }
3911
3912 %extend foo::bar {
3913    Integer add(Integer x, Integer y) {
3914        Integer r = x + y;        // Error. Integer not defined in this scope
3915        return r;
3916    }
3917 };
3918 </pre>
3919 </div>
3920
3921 <p>
3922 In this case, SWIG correctly resolves the added method parameters and return type to
3923 <tt>foo::Integer</tt>.  However, since function bodies aren't parsed and such code is
3924 emitted in the global namespace, this code produces a compiler error about <tt>Integer</tt>. 
3925 To fix the problem, make sure you use fully qualified names.  For example:
3926 </p>
3927
3928 <div class="code">
3929 <pre>
3930 %extend foo::bar {
3931    Integer add(Integer x, Integer y) {
3932        foo::Integer r = x + y;        // Ok.
3933        return r;
3934    }
3935 };
3936 </pre>
3937 </div>
3938
3939 <p>
3940 <b>Note:</b> SWIG does <em>not</em> propagate <tt>using</tt> declarations to
3941 the resulting wrapper code.   If these declarations appear in an interface,
3942 they should <em>also</em> appear in any header files that might have been 
3943 included in a <tt>%{ ... %}</tt> section.  In other words, don't insert extra
3944 <tt>using</tt> declarations into a SWIG interface unless they also appear
3945 in the underlying C++ code.
3946 </p>
3947
3948 <p>
3949 <b>Note:</b> Code inclusion directives such as <tt>%{ ... %}</tt> or
3950 <tt>%inline %{ ... %}</tt> should not be placed inside a namespace declaration.  
3951 The code emitted by these directives will not be enclosed in a namespace and
3952 you may get very strange results.  If you need to use namespaces with
3953 these directives, consider the following:
3954 </p>
3955
3956 <div class="code">
3957 <pre>
3958 // Good version
3959 %inline %{
3960 namespace foo {
3961      void bar(int) { ... }
3962      ...
3963 }
3964 %}
3965
3966 // Bad version.  Emitted code not placed in namespace.
3967 namespace foo {
3968 %inline %{
3969      void bar(int) { ... }   /* I'm bad */
3970      ...
3971 %}
3972 }
3973 </pre>
3974 </div>
3975
3976 <p>
3977 <b>Note:</b> When the <tt>%extend</tt> directive is used inside a namespace, the namespace name is
3978 included in the generated functions. For example, if you have code like this,
3979 </p>
3980
3981 <div class="code">
3982 <pre>
3983 namespace foo {
3984    class bar {
3985    public:
3986         %extend {
3987            int blah(int x);
3988         };
3989    };
3990 }
3991 </pre>
3992 </div>
3993
3994 <p>
3995 the added method <tt>blah()</tt> is mapped to a function <tt>int foo_bar_blah(foo::bar *self, int x)</tt>.
3996 This function resides in the global namespace.
3997 </p>
3998
3999 <p>
4000 <b>Note:</b> Although namespaces are flattened in the target language, the SWIG generated wrapper
4001 code observes the same namespace conventions as used in the input file.  Thus, if there are no symbol
4002 conflicts in the input, there will be no conflicts in the generated code. 
4003 </p>
4004
4005 <p>
4006 <b>Note:</b> In the same way that no resolution is performed on parameters, a conversion operator name must match exactly to how it is defined. Do not change the qualification of the operator. For example, suppose you had an interface like this:
4007 </p>
4008
4009 <div class="code">
4010 <pre>
4011 namespace foo {
4012    class bar;
4013    class spam {
4014    public:
4015         ...
4016         operator bar();      // Conversion of spam -&gt; bar
4017         ...
4018    };
4019 }
4020 </pre>
4021 </div>
4022
4023 <p>
4024 The following is how the feature is expected to be written for a successful match:
4025 </p>
4026
4027 <div class="code">
4028 <pre>
4029 %rename(tofoo) foo::spam::operator bar();
4030 </pre>
4031 </div>
4032
4033 <p>
4034 The following does not work as no namespace resolution is performed in the matching of conversion operator names:
4035 </p>
4036
4037 <div class="code">
4038 <pre>
4039 %rename(tofoo) foo::spam::operator <b>foo::</b>bar();
4040 </pre>
4041 </div>
4042
4043 <p>
4044 Note, however, that if the operator is defined using a qualifier in its name, then the feature must use it too...
4045 </p>
4046
4047 <div class="code">
4048 <pre>
4049 %rename(tofoo) foo::spam::operator bar();      // will not match
4050 %rename(tofoo) foo::spam::operator foo::bar(); // will match
4051 namespace foo {
4052    class bar;
4053    class spam {
4054    public:
4055         ...
4056         operator foo::bar();
4057         ...
4058    };
4059 }
4060 </pre>
4061 </div>
4062
4063 <p>
4064 <b>Compatibility Note:</b> Versions of SWIG prior to 1.3.32 were inconsistent in this approach. A fully qualified name was usually required, but would not work in some situations.
4065 </p>
4066
4067
4068 <p>
4069 <b>Note:</b> The flattening of namespaces is only intended to serve as
4070 a basic namespace implementation.  
4071 None of the target language modules are currently programmed
4072 with any namespace awareness.   In the future, language modules may or may not provide
4073 more advanced namespace support.
4074 </p>
4075
4076 <H2><a name="SWIGPlus_renaming_templated_types_namespaces"></a>6.20 Renaming templated types in namespaces</H2>
4077
4078
4079 <p>
4080 As has been mentioned, when %rename includes parameters, the parameter types must match exactly (no typedef or namespace resolution is performed).
4081 SWIG treats templated types slightly differently and has an additional matching rule so unlike non-templated types, an exact match is not always required.
4082 If the fully qualified templated type is specified, it will have a higher precedence over the generic template type.
4083 In the example below, the generic template type is used to rename to <tt>bbb</tt> and the fully qualified type is used to rename to <tt>ccc</tt>.
4084 </p>
4085
4086 <div class="code">
4087 <pre>
4088 %rename(bbb) Space::ABC::aaa(T t);                       // will match but with lower precedence than ccc
4089 %rename(ccc) Space::ABC&lt;Space::XYZ&gt;::aaa(Space::XYZ t);  // will match but with higher precedence than bbb
4090
4091 namespace Space {
4092   class XYZ {};
4093   template&lt;typename T&gt; struct ABC {
4094     void aaa(T t) {}
4095   };
4096 }
4097 %template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
4098 </pre>
4099 </div>
4100
4101 <p>
4102 It should now be apparent that there are many ways to achieve a renaming with %rename. This is demonstrated
4103 by the following two examples, which are effectively the same as the above example.
4104 Below shows how %rename can be placed inside a namespace.
4105 </p>
4106
4107 <div class="code">
4108 <pre>
4109 namespace Space {
4110   %rename(bbb) ABC::aaa(T t);                       // will match but with lower precedence than ccc
4111   %rename(ccc) ABC&lt;Space::XYZ&gt;::aaa(Space::XYZ t);  // will match but with higher precedence than bbb
4112   %rename(ddd) ABC&lt;Space::XYZ&gt;::aaa(XYZ t);         // will not match
4113 }
4114
4115 namespace Space {
4116   class XYZ {};
4117   template&lt;typename T&gt; struct ABC {
4118     void aaa(T t) {}
4119   };
4120 }
4121 %template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
4122 </pre>
4123 </div>
4124
4125 <p>
4126 Note that <tt>ddd</tt> does not match as there is no namespace resolution for parameter types and the fully qualified type must be specified for template type expansion.
4127 The following example shows how %rename can be placed within %extend.
4128 </p>
4129
4130 <div class="code">
4131 <pre>
4132 namespace Space {
4133   %extend ABC {
4134     %rename(bbb) aaa(T t);           // will match but with lower precedence than ccc
4135   }
4136   %extend ABC&lt;Space::XYZ&gt; {
4137     %rename(ccc) aaa(Space::XYZ t);  // will match but with higher precedence than bbb
4138     %rename(ddd) aaa(XYZ t);         // will not match
4139   }
4140 }
4141
4142 namespace Space {
4143   class XYZ {};
4144   template&lt;typename T&gt; struct ABC {
4145     void aaa(T t) {}
4146   };
4147 }
4148 %template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
4149 </pre>
4150 </div>
4151
4152
4153 <H2><a name="SWIGPlus_exception_specifications"></a>6.21 Exception specifications</H2>
4154
4155
4156 <p>
4157 When C++ programs utilize exceptions, exceptional behavior is sometimes specified as
4158 part of a function or method declaration.  For example:
4159 </p>
4160
4161 <div class="code">
4162 <pre>
4163 class Error { };
4164
4165 class Foo {
4166 public:
4167     ...
4168     void blah() throw(Error);
4169     ...
4170 };
4171 </pre>
4172 </div>
4173
4174 <p>
4175 If an exception specification is used, SWIG automatically generates
4176 wrapper code for catching the indicated exception and, when possible,
4177 rethrowing it into the target language, or converting it into an error
4178 in the target language otherwise. For example, in Python, you can
4179 write code like this:
4180 </p>
4181
4182 <div class="targetlang">
4183 <pre>
4184 f = Foo()
4185 try:
4186     f.blah()
4187 except Error,e:
4188      # e is a wrapped instance of "Error"
4189 </pre>
4190 </div>
4191
4192 <p>
4193 Details of how to tailor code for handling the caught C++ exception and converting it into the target language's exception/error handling mechanism
4194 is outlined in the <a href="Typemaps.html#throws_typemap">"throws" typemap</a> section.
4195 </p>
4196
4197 <p>
4198 Since exception specifications are sometimes only used sparingly, this alone may not be enough to
4199 properly handle C++ exceptions. To do that, a different set of special SWIG directives are used.
4200 Consult the "<a href="Customization.html#exception">Exception handling with %exception</a>" section for details.
4201 The next section details a way of simulating an exception specification or replacing an existing one.
4202 </p>
4203
4204 <H2><a name="SWIGPlus_catches"></a>6.22 Exception handling with %catches</H2>
4205
4206
4207 <p>
4208 Exceptions are automatically handled for methods with an exception specification.
4209 Similar handling can be achieved for methods without exception specifications through the <tt>%catches</tt> feature.
4210 It is also possible to replace any declared exception specification using the <tt>%catches</tt> feature.
4211 In fact, <tt>%catches</tt> uses the same <a href="Typemaps.html#throws_typemap">"throws" typemaps</a> that SWIG uses for exception specifications in handling exceptions.
4212 The <tt>%catches</tt> feature must contain a list of possible types that can be thrown.
4213 For each type that is in the list, SWIG will generate a catch handler, in the same way that it would for types declared in the exception specification.
4214 Note that the list can also include the catch all specification "...".
4215 For example,
4216 </p>
4217
4218 <div class="code">
4219 <pre>
4220 struct EBase { virtual ~EBase(); };
4221 struct Error1 : EBase { };
4222 struct Error2 : EBase { };
4223 struct Error3 : EBase { };
4224 struct Error4 : EBase { };
4225
4226 %catches(Error1,Error2,...) Foo::bar();
4227 %catches(EBase) Foo::blah();
4228
4229 class Foo {
4230 public:
4231     ...
4232     void bar();
4233     void blah() throw(Error1,Error2,Error3,Error4);
4234     ...
4235 };
4236 </pre>
4237 </div>
4238
4239 <p>
4240 For the <tt>Foo::bar()</tt> method, which can throw anything,
4241 SWIG will generate catch handlers for <tt>Error1</tt>, <tt>Error2</tt> as well as a catch all handler (...).
4242 Each catch handler will convert the caught exception and convert it into a target language error/exception.
4243 The catch all handler will convert the caught exception into an unknown error/exception.
4244 </p>
4245
4246 <p>
4247 Without the <tt>%catches</tt> feature being attached to <tt>Foo::blah()</tt>,
4248 SWIG will generate catch handlers for all of the types in the exception specification, that is, <tt>Error1, Error2, Error3, Error4</tt>.
4249 However, with the <tt>%catches</tt> feature above,
4250 just a single catch handler for the base class, <tt>EBase</tt> will be generated to convert the C++ exception into a target language error/exception.
4251 </p>
4252
4253
4254 <H2><a name="SWIGPlus_nn33"></a>6.23 Pointers to Members</H2>
4255
4256
4257 <p>
4258 Starting with SWIG-1.3.7, there is limited parsing support for pointers to C++ class members.
4259 For example:
4260 </p>
4261
4262 <div class="code">
4263 <pre>
4264 double do_op(Object *o, double (Object::*callback)(double,double));
4265 extern double (Object::*fooptr)(double,double);
4266 %constant double (Object::*FOO)(double,double) = &amp;Object::foo;
4267 </pre>
4268 </div>
4269
4270 <p>
4271 Although these kinds of pointers can be parsed and represented by the
4272 SWIG type system, few language modules know how to handle them due to
4273 implementation differences from standard C pointers.  Readers are
4274 <em>strongly</em> advised to consult an advanced text such as the "The
4275 Annotated C++ Manual" for specific details.
4276 </p>
4277
4278 <p>
4279 When pointers to members are supported, the pointer value might appear as a special
4280 string like this:
4281 </p>
4282
4283 <div class="targetlang">
4284 <pre>
4285 &gt;&gt;&gt; print example.FOO
4286 _ff0d54a800000000_m_Object__f_double_double__double
4287 &gt;&gt;&gt;
4288 </pre>
4289 </div>
4290
4291 <p>
4292 In this case, the hexadecimal digits represent the entire value of the
4293 pointer which is usually the contents of a small C++ structure on most
4294 machines.
4295 </p>
4296
4297 <p>
4298 SWIG's type-checking mechanism is also more limited when working with
4299 member pointers.  Normally SWIG tries to keep track of inheritance
4300 when checking types.  However, no such support is currently provided
4301 for member pointers.
4302 </p>
4303
4304 <H2><a name="SWIGPlus_nn34"></a>6.24 Smart pointers and operator-&gt;()</H2>
4305
4306
4307 <p>
4308 In some C++ programs, objects are often encapsulated by smart-pointers
4309 or proxy classes.   This is sometimes done to implement automatic memory management (reference counting) or
4310 persistence. Typically a smart-pointer is defined by a template class where
4311 the <tt>-&gt;</tt> operator has been overloaded.  This class is then wrapped
4312 around some other class.  For example:
4313 </p>
4314
4315 <div class="code">
4316 <pre>
4317 // Smart-pointer class
4318 template&lt;class T&gt; class SmartPtr {
4319     T *pointee;
4320 public:
4321     ...
4322     T *operator-&gt;() {
4323         return pointee;
4324     }
4325     ...
4326 };
4327
4328 // Ordinary class
4329 class Foo_Impl {
4330 public:
4331     int x;
4332     virtual void bar();
4333     ...
4334 };
4335
4336 // Smart-pointer wrapper
4337 typedef SmartPtr&lt;Foo_Impl&gt; Foo;
4338
4339 // Create smart pointer Foo
4340 Foo make_Foo() {
4341     return SmartPtr(new Foo_Impl());
4342 }
4343
4344 // Do something with smart pointer Foo
4345 void do_something(Foo f) {
4346     printf("x = %d\n", f-&gt;x);
4347     f-&gt;bar();
4348 }
4349 </pre>
4350 </div>
4351
4352 <p>
4353 A key feature of this approach is that by defining
4354 <tt>operator-&gt;</tt> the methods and attributes of the object
4355 wrapped by a smart pointer are transparently accessible.  For example,
4356 expressions such as these (from the previous example),
4357 </p>
4358
4359 <div class="code">
4360 <pre>
4361 f-&gt;x
4362 f-&gt;bar()
4363 </pre>
4364 </div>
4365
4366 <p>
4367 are transparently mapped to the following
4368 </p>
4369
4370 <div class="code">
4371 <pre>
4372 (f.operator-&gt;())-&gt;x;
4373 (f.operator-&gt;())-&gt;bar();
4374 </pre>
4375 </div>
4376
4377 <p>
4378 When generating wrappers, SWIG tries to emulate this functionality to
4379 the extent that it is possible.  To do this, whenever
4380 <tt>operator-&gt;()</tt> is encountered in a class, SWIG looks at its
4381 returned type and uses it to generate wrappers for accessing
4382 attributes of the underlying object.  For example, wrapping the above
4383 code produces wrappers like this:
4384 </p>
4385
4386 <div class="code">
4387 <pre>
4388 int Foo_x_get(Foo *f) {
4389    return (*f)-&gt;x;
4390 }
4391 void Foo_x_set(Foo *f, int value) {
4392    (*f)-&gt;x = value;
4393 }
4394 void Foo_bar(Foo *f) {
4395    (*f)-&gt;bar();
4396 }
4397 </pre>
4398 </div>
4399
4400 <p>
4401 These wrappers take a smart-pointer instance as an argument, but
4402 dereference it in a way to gain access to the object returned by
4403 <tt>operator-&gt;()</tt>.  You should carefully compare these wrappers
4404 to those in the first part of this chapter (they are slightly
4405 different).
4406 </p>
4407
4408 <p>
4409 The end result is that access looks very similar to C++.  For
4410 example, you could do this in Python:
4411 </p>
4412
4413 <div class="targetlang">
4414 <pre>
4415 &gt;&gt;&gt; f = make_Foo()
4416 &gt;&gt;&gt; print f.x
4417 0
4418 &gt;&gt;&gt; f.bar()
4419 &gt;&gt;&gt;
4420 </pre>
4421 </div>
4422
4423 <p>
4424 When generating wrappers through a smart-pointer, SWIG tries to
4425 generate wrappers for all methods and attributes that might be
4426 accessible through <tt>operator-&gt;()</tt>.  This includes any methods
4427 that might be accessible through inheritance.   However, there are a number of restrictions:
4428 </p>
4429
4430 <ul>
4431 <li>Member variables and methods are wrapped through a smart
4432 pointer. Enumerations, constructors, and destructors are not wrapped.
4433 </li>
4434
4435 <li><p>If the smart-pointer class and the underlying object both define a method or
4436 variable of the same name, then the smart-pointer version has precedence.   For
4437 example, if you have this code</p>
4438
4439 <div class="code">
4440 <pre>
4441 class Foo {
4442 public:
4443     int x;
4444 };
4445
4446 class Bar {
4447 public:
4448     int x;       
4449     Foo *operator-&gt;();
4450 };
4451 </pre>
4452 </div>
4453
4454 <p>
4455 then the wrapper for <tt>Bar::x</tt> accesses the <tt>x</tt> defined in <tt>Bar</tt>, and 
4456 not the <tt>x</tt> defined in <tt>Foo</tt>.</p>
4457 </li>
4458 </ul>
4459
4460 <p>
4461 If your intent is to only expose the smart-pointer class in the interface, it is not necessary to wrap both
4462 the smart-pointer class and the class for the underlying object.  However, you must still tell SWIG about both
4463 classes if you want the technique described in this section to work.   To only generate wrappers for the
4464 smart-pointer class, you can use the %ignore directive.  For example:
4465 </p>
4466
4467 <div class="code">
4468 <pre>
4469 %ignore Foo;
4470 class Foo {       // Ignored
4471 };
4472
4473 class Bar {
4474 public:
4475    Foo *operator-&gt;();
4476    ...
4477 };
4478 </pre>
4479 </div>
4480
4481 <p>
4482 Alternatively, you can import the definition of <tt>Foo</tt> from a separate file using
4483 <tt>%import</tt>.
4484 </p>
4485  
4486 <p>
4487 <b>Note:</b> When a class defines <tt>operator-&gt;()</tt>, the operator itself is wrapped
4488 as a method <tt>__deref__()</tt>.  For example:
4489 </p>
4490
4491 <div class="targetlang">
4492 <pre>
4493 f = Foo()               # Smart-pointer
4494 p = f.__deref__()       # Raw pointer from operator-&gt;
4495 </pre>
4496 </div>
4497
4498 <p>
4499 <b>Note:</b> To disable the smart-pointer behavior, use <tt>%ignore</tt> to ignore
4500 <tt>operator-&gt;()</tt>.  For example:
4501 </p>
4502
4503 <div class="code">
4504 <pre>
4505 %ignore Bar::operator-&gt;;
4506 </pre>
4507 </div>
4508
4509 <p>
4510 <b>Note:</b> Smart pointer support was first added in SWIG-1.3.14.
4511 </p>
4512
4513
4514 <H2><a name="SWIGPlus_nn35"></a>6.25 Using declarations and inheritance</H2>
4515
4516
4517 <p>
4518 <tt>using</tt> declarations are sometimes used to adjust access to members of
4519 base classes.  For example:
4520 </p>
4521
4522 <div class="code">
4523 <pre>
4524 class Foo {
4525 public:
4526       int  blah(int x);
4527 };
4528
4529 class Bar {
4530 public:
4531       double blah(double x);
4532 };
4533
4534 class FooBar : public Foo, public Bar {
4535 public:
4536       using Foo::blah;  
4537       using Bar::blah;
4538       char *blah(const char *x);
4539 };
4540 </pre>
4541 </div>
4542
4543 <p>
4544 In this example, the <tt>using</tt> declarations make different
4545 versions of the overloaded <tt>blah()</tt> method accessible from the
4546 derived class.  For example:
4547 </p>
4548
4549 <div class="code">
4550 <pre>
4551 FooBar *f;
4552 f-&gt;blah(3);         // Ok. Invokes Foo::blah(int)
4553 f-&gt;blah(3.5);       // Ok. Invokes Bar::blah(double)
4554 f-&gt;blah("hello");   // Ok. Invokes FooBar::blah(const char *);
4555 </pre>
4556 </div>
4557
4558 <p>
4559 SWIG emulates the same functionality when creating wrappers.  For example, if
4560 you wrap this code in Python, the module works just like you would expect:
4561 </p>
4562
4563 <div class="targetlang">
4564 <pre>
4565 &gt;&gt;&gt; import example
4566 &gt;&gt;&gt; f = example.FooBar()
4567 &gt;&gt;&gt; f.blah(3)
4568 &gt;&gt;&gt; f.blah(3.5)
4569 &gt;&gt;&gt; f.blah("hello")
4570 </pre>
4571 </div>
4572
4573 <p>
4574 <tt>using</tt> declarations can also be used to change access when applicable.  For example:
4575 </p>
4576
4577 <div class="code">
4578 <pre>
4579 class Foo {
4580 protected:
4581     int x;
4582     int blah(int x);
4583 };
4584
4585 class Bar : public Foo {
4586 public:
4587     using Foo::x;       // Make x public
4588     using Foo::blah;    // Make blah public
4589 };
4590 </pre>
4591 </div>
4592
4593 <p>
4594 This also works in SWIG---the exposed declarations will be wrapped normally.
4595 </p>
4596
4597 <p>
4598 When <tt>using</tt> declarations are used as shown in these examples, declarations
4599 from the base classes are copied into the derived class and wrapped normally.  When
4600 copied, the declarations retain any properties that might have been attached using
4601 <tt>%rename</tt>, <tt>%ignore</tt>, or <tt>%feature</tt>.  Thus, if a method is
4602 ignored in a base class, it will also be ignored by a <tt>using</tt> declaration.
4603 </p>
4604
4605 <p>
4606 Because a <tt>using</tt> declaration does not provide fine-grained
4607 control over the declarations that get imported, it may be difficult
4608 to manage such declarations in applications that make heavy use of
4609 SWIG customization features.  If you can't get <tt>using</tt> to work
4610 correctly, you can always change the interface to the following:
4611 </p>
4612
4613 <div class="code">
4614 <pre>
4615
4616 class FooBar : public Foo, public Bar {
4617 public:
4618 #ifndef SWIG
4619       using Foo::blah;  
4620       using Bar::blah;
4621 #else
4622       int blah(int x);         // explicitly tell SWIG about other declarations
4623       double blah(double x);
4624 #endif
4625
4626       char *blah(const char *x);
4627 };
4628 </pre>
4629 </div>
4630
4631 <p>
4632 <b>Notes:</b>
4633 </p>
4634
4635 <ul>
4636 <li><p>If a derived class redefines a method defined in a base class, then a <tt>using</tt> declaration
4637 won't cause a conflict.  For example:</p>
4638
4639 <div class="code">
4640 <pre>
4641 class Foo {
4642 public:
4643        int blah(int );
4644        double blah(double);
4645 };
4646
4647 class Bar : public Foo {
4648 public:
4649        using Foo::blah;    // Only imports blah(double);
4650        int blah(int);
4651 };
4652 </pre>
4653 </div>
4654
4655 <li><p>Resolving ambiguity in overloading may prevent declarations from being
4656 imported by <tt>using</tt>.  For example:
4657 </p>
4658
4659 <div class="code">
4660 <pre>
4661 %rename(blah_long) Foo::blah(long);
4662 class Foo {
4663 public:
4664      int blah(int);
4665      long blah(long);  // Renamed to blah_long
4666 };
4667
4668 class Bar : public Foo {
4669 public:
4670      using Foo::blah;     // Only imports blah(int)
4671      double blah(double x);
4672 };
4673 </pre>
4674 </div>
4675 </ul>
4676
4677 <H2><a name="SWIGPlus_nested_classes"></a>6.26 Nested classes</H2>
4678
4679
4680 <p>
4681 There is limited support for nested structs and unions when wrapping C code, see <a href="SWIG.html#SWIG_nested_structs">Nested structures</a> for further details.
4682 However, there is no nested class/struct/union support when wrapping C++ code (using the -c++ commandline option).
4683 This may be added at a future date, however, until then some of the following workarounds can be applied.
4684 </p>
4685
4686 <p>
4687 It might be possible to use partial class information.  Since
4688 SWIG does not need the entire class specification to work, conditional
4689 compilation can be used to comment out the problematic nested class definition, you might do this:
4690 </p>
4691
4692 <div class="code">
4693 <pre>
4694 class Foo {
4695 public:
4696 #ifndef SWIG
4697    class Bar {
4698    public:
4699      ...
4700    };
4701 #endif
4702    Foo();
4703   ~Foo();
4704    ...
4705 };
4706 </pre>
4707 </div>
4708
4709 <p>
4710 The next workaround assumes you cannot modify the source code as was done above and it provides a solution for methods that use nested class types.
4711 Imagine we are wrapping the <tt>Outer</tt> class which contains a nested class <tt>Inner</tt>:
4712 </p>
4713
4714 <div class="code">
4715 <pre>
4716 // File outer.h
4717 class Outer {
4718 public:
4719   class Inner {
4720     public:
4721       int var;
4722       Inner(int v = 0) : var(v) {}
4723   };
4724   void method(Inner inner);
4725 };
4726 </pre>
4727 </div>
4728
4729 <p>
4730 The following interface file works around SWIG nested class limitations by redefining the nested class as a global class.
4731 A typedef for the compiler is also required in order for the generated wrappers to compile.
4732 </p>
4733
4734 <div class="code">
4735 <pre>
4736 // File : example.i
4737 %module example
4738
4739 // Suppress SWIG warning
4740 #pragma SWIG nowarn=SWIGWARN_PARSE_NESTED_CLASS
4741
4742 // Redefine nested class in global scope in order for SWIG to generate
4743 // a proxy class. Only SWIG parses this definition.
4744 class Inner {
4745   public:
4746     int var;
4747     Inner(int v = 0) : var(v) {}
4748 };
4749
4750 %{
4751 #include "outer.h"
4752 %}
4753 %include "outer.h"
4754
4755 %{
4756 // SWIG thinks that Inner is a global class, so we need to trick the C++
4757 // compiler into understanding this so called global type.
4758 typedef Outer::Inner Inner;
4759 %}
4760
4761 </pre>
4762 </div>
4763
4764 <p>
4765 The downside to this approach is having to maintain two definitions of <tt>Inner</tt>, the real one and the one in the interface file that SWIG parses.
4766 </p>
4767
4768 <H2><a name="SWIGPlus_nn37"></a>6.27 A brief rant about const-correctness</H2>
4769
4770
4771 <p>
4772 A common issue when working with C++ programs is dealing with all
4773 possible ways in which the <tt>const</tt> qualifier (or lack thereof)
4774 will break your program, all programs linked against your program, and
4775 all programs linked against those programs.  
4776 </p>
4777
4778 <p>
4779 Although SWIG knows how to correctly deal with <tt>const</tt> in its
4780 internal type system and it knows how to generate wrappers that are
4781 free of const-related warnings, SWIG does not make any attempt to preserve 
4782 const-correctness in the target language.  Thus, it is possible to
4783 pass <tt>const</tt> qualified objects to non-const methods and functions.
4784 For example, consider the following code in C++:
4785 </p>
4786
4787 <div class="code">
4788 <pre>
4789 const Object * foo();
4790 void bar(Object *);
4791
4792 ...
4793 // C++ code
4794 void blah() {
4795    bar(foo());         // Error: bar discards const
4796 };
4797 </pre>
4798 </div>
4799
4800 <p>
4801 Now, consider the behavior when wrapped into a Python module:
4802 </p>
4803
4804 <div class="targetlang">
4805 <pre>
4806 &gt;&gt;&gt; bar(foo())         # Okay
4807 &gt;&gt;&gt; 
4808 </pre>
4809 </div>
4810
4811 <p>
4812 Although this is clearly a violation of the C++ type-system, fixing
4813 the problem doesn't seem to be worth the added implementation
4814 complexity that would be required to support it in the SWIG run-time type
4815 system.  There are no plans to change this in future releases
4816 (although we'll never rule anything out entirely).
4817 </p>
4818
4819 <p>
4820 The bottom line is that this particular issue does not appear to be a problem
4821 for most SWIG projects.    Of course, you might want to consider
4822 using another tool if maintaining constness is the most important part
4823 of your project.
4824 </p>
4825
4826 <H2><a name="SWIGPlus_nn42"></a>6.28 Where to go for more information</H2>
4827
4828
4829 <p>
4830 If you're wrapping serious C++ code, you might want to pick up a copy
4831 of "The Annotated C++ Reference Manual" by Ellis and Stroustrup.  This
4832 is the reference document we use to guide a lot of SWIG's C++ support.
4833 </p>
4834
4835 </body>
4836 </html>
4837
4838 <!--  LocalWords:  destructors Enums Namespaces const SWIG's STL OO adaptor tcl
4839  -->
4840 <!--  LocalWords:  debuggable cxx OBJS Wiki accessor nodefault makedefault
4841  -->
4842 <!--  LocalWords:  notabstract CopyFoo
4843  -->