Correct syntax for a friend function of a template class

Discussion in 'C++' started by Andy Champ, Mar 25, 2008.

  1. Andy Champ

    Andy Champ Guest

    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
    Andy Champ, Mar 25, 2008
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Oplec
    Replies:
    5
    Views:
    601
    Oplec
    Oct 28, 2003
  2. Yueh-Wei Hu
    Replies:
    0
    Views:
    447
    Yueh-Wei Hu
    May 23, 2004
  3. Replies:
    2
    Views:
    478
    John Harrison
    Nov 9, 2005
  4. =?gb2312?B?wfXquw==?=
    Replies:
    10
    Views:
    697
    Victor Bazarov
    Aug 1, 2007
  5. A L
    Replies:
    1
    Views:
    510
    Alf P. Steinbach /Usenet
    Aug 25, 2010
Loading...

Share This Page