[TriLUG] OT: C++ Question

Tanner Lovelace clubjuggler at gmail.com
Tue Jan 31 00:42:32 EST 2006


On 1/30/06, Randy Barlow <rpbarlow at ncsu.edu> wrote:
> Sorry for the OT post, but this problem is driving me nuts!  (If anyone
> knows of a *good* mailing list that this question would be more
> appropriate for, please let me know!)

At one point we had a development list, but it went the way of the
dodo.  So, I think you're not off-topic at all.

> The problem: I'm getting a compiler error for the following class
> definition:
[...snip...]
>         vector3d operator+ (vector3d);
>         point3d operator+ (vector3d);

As the other person said, there is no way for the compiler to
determine which function should be called for any given
function call because overloading only works on arguments,
not on return type.  You'll need to rethink your class.

Interestingly enough, the Feb 2006 edition of the C/C++
Users Journal has an article on operator overloading on
page 25.  The example it uses is a 3d vector class and how
to unambiguously specify dot and cross products.  It also
shows how, if you really want to, you can use a proxy class
pattern to achieve Return Type Overloading.  The trick is
that you don't return a point3d or vector3d.  Instead, you
return an intermediate class that upon conversion to the
requested type, calls the correct function call.  For example
suppose you change your two overloaded functions and
call them something else and change the operator like this:

class point3d {
...
point3d add_and_ret_p3d(vector3d);
vector3d add_and_ret_v3d(vector3d);
}

You then create the VectorSum class to be convertible to either a
point3d or a vector3d depending on how it is referenced, like this:

class VectorSum
{
friend VectorSum operator+(const point3d& lhs, const vector3d& rhs)  {
     return VectorSum(lhs, rhs); }

VectorSum(const point3d& _lhs, const vector3d& _rhs) :
   lhs(_lhs), rhs(_rhs) {}

const point3d& lhs;
const vector3d& rhs;

public:

  operator point3d() const { return lhs.add_and_ret_p3d(rhs); }

  operator vector3d() const { return lhs.add_and_ret_v3d(rhs)

};

So, the + operator always returns a VectorSum object and the
conversion operators take care of converting it to the appropriate
type and making sure the correct function is called.

See the article for _much_ more detail (and to fix any errors
that I'm sure I've introduced here).

Cheers,
Tanner

--
Tanner Lovelace
clubjuggler at gmail dot com
http://wtl.wayfarer.org/
(fieldless) In fess two roundels in pale, a billet fesswise and an
increscent, all sable.



More information about the TriLUG mailing list