Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Correct syntax for a friend function of a template class

Thread Tools

Correct syntax for a friend function of a template class

Andy Champ
Posts: n/a
We've had code similar to this in our project for ages:

template <typename T> class Test
Test(T Value): Datum(Value) {};
T Datum;

template <typename U>
friend bool operator==(Test<T> left, Test<U> right);

template <typename T, typename U>
bool operator==(Test<T> left, Test<U> right)
return left.Datum == right.Datum;

int main()
Test<int> ti = 1;
Test<long> tl = 1;
ti == tl;
return 0;

(obviously this is a simplified version)

We tend to run with MS compilers. This all compiled fine with MS VC
2003 and 2005; but now we're trying the new 2008 compiler, and it
didn't build. Instead the friend declaration has to change to

template <typename T, typename U>
friend bool operator==(Test<T> left, Test<U> right);

Having been bitten once, I found someone with G++ and fed it to that.
g++ objected to both versions, and I had to change to

template <typename Q, typename U>
friend bool operator==(Test<Q> left, Test<U> right);

That works, and I'm pretty sure it is standard - but it doesn't do
*quite* what I want, it's too liberal. It states that an operator==
which takes any two Test objects specialised with any template
parameters is a friend - not just one where the left op is templated
with the same type as the original class.

I did a little digging, and found a page by Danny Kalev that recommends
exactly the syntax we have, and I've done a search in the history of
this group and found nothing useful.

Can someone tell me what the correct, ANSI compliant, syntax is?


Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Declaring a template class with two template params a friend in anon-template class A L C++ 1 08-25-2010 07:25 AM
How can I declare and define a friend template function in a template class? =?gb2312?B?wfXquw==?= C++ 10 08-01-2007 01:48 AM
Problem with defining template friend function of a template class. C++ 2 11-09-2005 08:27 PM
using friend function template in class template Yueh-Wei Hu C++ 0 05-23-2004 11:36 AM
Correct syntax for class templates that declare friend functions Oplec C++ 5 10-28-2003 01:51 PM