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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.