Marcel Müller <> writes:
> On 04.11.2011 15:01, Urs Thuermann wrote:
> > I tried overloading the operator<<() for ostream as a static member
> > function in a class, but the compiler (gcc) complained that it should
> > be non-static or non-member. Why is this not possible? Since I want
> > to pass a private type of the class as argument, this is a problem.
>
> > class Foo {
> > struct Bar {
> > public:
> > static ostream&operator<<(ostream&os, const Bar&b)
> > {
> > b.print(os);
> > return os;
> > }
>
> > I cannot make the operator<< a non-member function since its parameter
> > type Bar is private and I'd prefer to leave it so. How should I solve
> > this?
>
> What's wrong with
> friend ostream&operator<<(ostream&os, const Bar&b);
> inside class Foo?
I am surprised that that works, because I have tried it before I
posted and gcc reported an error since the type Foo::Bar is private
and unusable outside class Foo. OK, I must have done something wrong,
since it now works, both, inline and outside of the class.
But now I've got the next question: How can I make that non-member
friend function static in foo.cc so it's not visible in other
translation units? (I know I can't use it anyway because I cannot
have object of type Foo::Bar, but I'd still prefer to have that
function staitc.)
When I try
friend static ostream &operator<<(ostream &os, const Bar &b);
in class Foo and
static ostream &operator<<(ostream &os, const Foo::Bar &b)
{
b.print(os);
return os;
}
outside any class in foo.cc I get the compiler message
error: storage class specifiers invalid in friend function declarations
and when I remove the static from the friend declaration I get
error: 'std:

stream& operator<<(std:

stream&, const Foo::Bar&)' was declared 'extern' and later 'static'
Without static in both places, everylooks looks fine.
But is there a way to have that operator<<() static?
urs