Sunday, February 19, 2006

Template Friend Functions

code snippet picked up from the net. don't remember where.

using namespace std;
class SomeClass{
T member;
friend ostream& operator<<(ostream &,SomeClass &);

ostream& operator<<(ostream &os, const SomeClass&some){
os<<"( " << some.member <<") ";
return os;

int main(int argc, char* argv[])
SomeClass sc(5);
cout << sc; // Problem????
return 0;

It reported that operator << was not found.

The problem is that in the class definition, a friend was declared as a function, not a template function. To make the code link properly, the friend declaration should be changed to:

friend ostream& operator<< <>(ostream &,SomeClass &);

Just another little C++ twist.

No comments: