Template question

B

BigBrian

I have some code, that resembles the following...

class Foo
{
template < class T >
Foo & operator << ( T const & t ) { ... }
};

class AnotherClass
{
friend Foo & operator << ( Foo &, AnotherClass & );
};

Foo & operator << ( Foo &, AnotherClass & )
{
....
}

int main()
{
Foo f;
AnotherClass a;

f << a;

}

The f << a; statemement above ends up calling the template function

Foo & Foo::eek:perator <<( AnotherClass const & )

however I want it to call the friend of Another class, ie

Foo & operator << ( Foo&, AnotherClass & )

How do I accomplish this? Basically, I want to limit the template
expansion of Foo::eek:perator << to NOT include AnotherClass as a
parameter, so the compiler finds the friend function to AnotherClass
instead. Any help is appreciated.

-Brian
 
M

msalters

BigBrian said:
I have some code, that resembles the following...

class Foo
{
template < class T >
Foo & operator << ( T const & t ) { ... }
};

class AnotherClass
{
friend Foo & operator << ( Foo &, AnotherClass & );
};

Foo & operator << ( Foo &, AnotherClass & )
{
...
}

int main()
{
Foo f;
AnotherClass a;

f << a;

}

The f << a; statemement above ends up calling the template function

Foo & Foo::eek:perator <<( AnotherClass const & )

however I want it to call the friend of Another class, ie

Foo & operator << ( Foo&, AnotherClass & )

That's logical: members are preferred over non-members.
The solution is simple:

class Foo
{
template < class T >
Foo & operator << ( T const & t ) { ... }
template < >
Foo & operator << <anotherClass> ( AnotherClass const & rhs ) {
operator<<( *this, rhs );
}
};
The specialization just refers to the non-member form.

Alternative: SFINAE or disable_if<T,AnotherClass> (use google)

HTH,
Michiel Salters
 
B

BigBrian

Thanks, but I didn't want to have to do this because now there's a
coupling between Foo and AnotherClass, that is Foo has to know about
AnotherClass. It would be nice if the calling code, ie the f << a ,
could choose somehow.

-Brian
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,663
Latest member
josh5959

Latest Threads

Top