(ref.doc)bs 140693
Next vinoski 150693
Prev: roland 240593
Up: Usenet
From: [email protected] (Bjarne Stroustrup)
Newsgroups: comp.lang.c++
Subject: Re: *NON* novice template question
Keywords: templates friends friend functions
Date: 14 Jun 93 23:34:57 GMT
Organization: AT&T Bell Laboratories, Murray Hill NJ
[email protected] (William Bulley @ Msen, Inc. -- Ann Arbor, Michigan) writes
> We have compromised with the following code, which *does* compile, but is
> not quite what we wanted to do nor had in mind at the outset:
#include <iostream.h>
template< int S >
class foo
{
private :
int a[S];
public :
friend ostream & operator << ( ostream & theStream, foo<S> & bah )
{
for (int i = 0; i < S; i++)
{
theStream << bah.a[i];
}
return theStream;
}
};
main()
{
foo<5> ccc;
cout << ccc;
return 0;
}
> What we would like to know is: does the friend function code have to be
> defined inside the class declartation for foo? In other words, is there a
> way to define operator << so it does not *have* to be an inline function?
>
> Any ideas or suggestions would be greatly appreciated. Thank you very much.
I assume that what you really wanted to write was something like:
template< int S >
class foo
{
private :
int a[S];
public :
friend ostream & operator << ( ostream & theStream, foo<S> & bah );
};
template<int S>
ostream & operator << ( ostream & theStream, foo<S> & bah )
{
for (int i = 0; i < S; i++)
{
theStream << bah.a[i];
}
return theStream;
}
However, that is ruled out by the rule that a template argument for a
functions template must be a type argument that can be determined
from an actual argument in a call. There is a proposal to relax that
rule to allow non-type template arguments that can be determined from
an actual argument in a call. I expect that to pass at the next meeting
or the one after, making the revised version of the example legal.
For now, you'll have to stick with the version you found unless your
compiler supplier has anticipated the standards committee. If you feel
uncomfortable having all of the code for the friend inline have the
inline contain a call to a member function that does the real work only.
automatically generated by info2www version 1.2.2.8