Thomas Tutone wrote:
Quote:
Pierre Barbier de Reuille wrote:
Quote:
>Hi,
>>
>after reading the article " The Standard Librarian : Defining Iterators
>and Const Iterators" from Matt Austern:
>
http://www.ddj.com/showArticle.jhtml...leID=184401331
>>
>I wanted to test using the non-template function friends of template
>classes. So I devised this code:
>>
[...]
Quote:
Quote:
>>
>It does compile but segfaults at runtime O_o
>Could someone explain to me what I did wrong ?
>
Add the two lines I indicated above, then re-compile and run your
program. I think you'll see the problem pretty quickly.
>
By the way, your program won't compile on Comeau, so I suspect your use
of templates is not correct. (But that is NOT the cause of your
described problem.)
>
Best regards,
>
Tom
>
Thank you very much, I corrected the mistake ... Here is the code which
is working (I put only the class definition):
template <class T>
struct S
{
friend S foo( const S& s1, const S& s2 )
{
return S( s1.s + s2.s );
}
friend T operator+( const S& a, const T& s )
{
return a+s.s;
}
friend T operator+( const S& s1, const S& s2 )
{
return s1.s + s2.s;
}
friend ostream& operator<<( ostream& s, const S& o )
{
s << "S(" << o.s << ")";
return s;
}
S( T a ) : s( a ) {}
T s;
};
As for the correctness, I think it *is* correct. At least, the use of
the non-template friend functions is even explicitly allowed by the norm
(cf. the article which even gives the precise § in the norm).
However, if you could give me the error, I would be very interested.
Thanks,
Pierre