http://www.perlmonks.org?node_id=989342


in reply to Re^2: Can't create XSUBs for C functions with a same name
in thread Can't create XSUBs for C functions with a same name

For what it's worth, Rob's code is also valid for C++ (and Inline::CPP):

use strict; use warnings; use Inline CPP => Config => BUILD_NOISY => 1; use Inline CPP => <<'EOCPP'; int add(SV * a, ...) { dXSARGS; int i, ret = 0; for(i = 0; i < items; i++) ret += SvIV(ST(i)); return ret; } EOCPP print add(11, 12), "\n"; # prints 23 print add(10, 11, 12), "\n"; # prints 33

...outputs...

23 33

While that's still not the same as function overloading, It's actually one of the best (clearest) examples I've seen anywhere on how to use the "..." parameter. I might have to add it to Inline::CPP's POD on some future release.

Another approach would be to use Inline::CPP, and wrap your functions in classes:

use strict; use warnings; use Inline CPP => Config => BUILD_NOISY => 1; use Inline CPP => 'DATA'; my $foo = Foo->new(); my $bar = Bar->new(); sub add { if( @_ == 2 ) { return $foo->add(@_); } return $bar->add(@_); } __DATA__ __CPP__ struct Foo { add( int a, int b ) { return a + b; } }; struct Bar { add( int a, int b, int c ) { return a + b + c } };

Of course with this process you're adding an additional Perl layer, so if your C++ subs are trivial, your performance will actually go down.

As the POD for Inline::CPP states, the module enables a large subset of C++, but not all of C++. Function overloading is one of those "not all" areas.


Dave