Sunday, February 19, 2006

Template Friend Functions

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


#include
using namespace std;
template
class SomeClass{
private:
T member;
public:
...
friend ostream& operator<<(ostream &,SomeClass &);
};

template
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: