Group: comp.lang.c++
From: James Kanze
Date: Friday, February 15, 2008 2:49 PM
Subject: Re: Operator as non-function

On Feb 15, 3:52 pm, saneman wrote:
> James Kanze wrote:
> > On Feb 15, 2:51 am, saneman wrote:

> Ok this version below works as you recommended:

> template< class A > class BOB;
> template< class A >
> BOB operator+(typename BOB::difference_type, BOB const& );

> template
> class BOB {
> private:
> typedef BOB
iterator;
> public:
> typedef typename A::difference_type difference_type;
> friend iterator operator + <> (difference_type i, const iterator& =
it);
> };

> But I don't understand the first 3 lines.

Just declarations, so that the symbols are known to the
compiler. You need to declare the operator+ function, so that
the compiler knows it is a template, and you need to declare the
class template BOB, in order to refer to it in the operator+
functions.

> In Bjarne Stroustrup C++PL
> C.13.2 page 854 he writes the following example:

> template class Matrix;
> template class Vector {
> T v[4];
> public:
> friend Vector operator *<> (const Matrix&, const Vector&);
> };

> So it seems that it should not be necessary to declare the
> operator as a template operator.

I thought you wanted it to be a template. If you don't, drop
the <>.

> I have C++ Templates by David Vandevoorde, but there is no
> info on this special rule, is there some documentation on the
> theory behind this example?

It's not a special rule, as far as I can see. The compiler
parses templates in two phases. In order to do so successfully,
it must know what symbols are templates, and what symbols are
the names of types---the grammar of C++ isn't context free.
That's why if the symbol is dependent, and unknown at the
point of use, you must tell the compiler that it is a template
or a typename. In this case, it's a little more complex,
because the symbol occurs in a context where preceding it by the
keyword "template" would cause ambiguities, or mean something
else. So you must declare is somewhere so that the compiler
will recognize it as a template.

Quite frankly, I wouldn't bother. I'd write a named member
function to do what I wanted, and then define the operator as a
template after, to call the named member function. So there'd
be no need of making it a friend.

--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34