Correct syntax for a friend function of a template class

A

Andy Champ

We've had code similar to this in our project for ages:

template <typename T> class Test
{
public:
Test(T Value): Datum(Value) {};
private:
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?

Thanks

Andy
 

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
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top