Overloading on return value (with a trick)
{ avoid using non-ASCII characters like '<' or '.' in your messages.
your posting software can most likely be set up not to allow those.
thanks! -mod }
As we know:
<.
struct TestFunky
{
int val;
char chr;
TestFunky( int v, char c)
: val(v)
, chr(c)
{}
};
int funky( TestFunky& v)
{
return v.val;
}
char funky( TestFunky& v) // compiler will not accept this overload!!!
{
return v.chr;
}
TestFunky testy( 666, 'E');
int i = funky(testy); // but we want to write it this way
char c = funky(testy); // but we want to write it this way
..>
doesn't work!
I've read a lot of (pseudo) arguments why this fact is a must. (I
disagree with (almost) all of them (as far as I remember). Anyway: it
is like it is.)
But there is a solution that solves the task (even though I don't
know, where it might make sense...):
<.
struct TestFunky
{
int val;
char chr;
TestFunky( int v, char c)
: val(v)
, chr(c)
{}
};
class funky
{
TestFunky& tf_;
public:
funky(TestFunky& tf)
: tf_(tf)
{}
operator int()
{
return tf_.val;
}
operator char()
{
return tf_.chr;
}
};
TestFunky testy( 666, 'E');
// and so we do as we wanted to.
int i = funky(testy);
char c = funky(testy);
// .and it even doesn't need more CPU load! (If the compiler isn't too
dumb.)
..>
Of course
<.
funky(testy); // doesn't work
..>
but e. g.
<.
(char)funky(testy); // works fine
..>
As I mentioned before, I don't have a good cause for that trick - just
a kind of finger exercise. ;-)
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]