Re: Class templates and friend function templates



BigMan wrote:
> I have a class template like this:
>
> template< typename t >
> class c;
>
> I'd also like to have an operator == for objects of types, which are
> different specializations of c:
> template< typename t1, typename t2 >
> bool operator ==
> (
> s< t1 > const&
> , s< t2 > const&
> );
>
> In order to implement this operator, I need it to be a friend of both
> s< t1 > and s< t2 >. For the sake of safety, I'd like no other
> specialization of c to have this operator as its friend. Is this
> possible and, if so, how?

Like this:

// Code
template <class T> class C;

template <class U, class V> bool operator ==(C<U>,C<V>);

template <class T> class C
{
public: C(int x_) : x(x_) {}

private: int x;

template <class U,class V>
friend bool operator == <T>(U u, V v);
};

template <class U, class V>
bool operator == (C<U> u, C<V> v)
{
return u.x == v.x;
}

int main()
{
C<int> c1(1);
C<float> c2(2);
bool b = c1 == c2;
}
// End of code

I'm actually not sure that this code is standard conforming, although it
seems like it should be. VC 7.1 likes it, but Comeau claims that the
template friend declaration is ill-formed.

-cd




.



Relevant Pages

  • Re: Circular Class Template Friendship
    ... > My issue is the syntax of declaring a friend class within ... > which the string is a fixed width that is specialized. ... it is still possible to have Name_Id_Table template ... the friend class declaration. ...
    (comp.lang.cpp)
  • Re: Class templates and friend function templates
    ... > It never occurred to me that the friend declaration could be an overload. ... > template ... I suspect the online version uses an EDG option to "instantiate ...
    (microsoft.public.vc.language)
  • Re: Template friendship to nested template class
    ... friend struct INNER; ... Probably you are missing an EXTRA template to declare ... I think it's because the name referred to in a 'friend' declaration is looked up to exist at the namespace scope. ...
    (microsoft.public.vc.language)
  • Re: Template friendship to nested template class
    ... template ... friend struct INNER; ... Both VC and gcc are happy with this code, but the intel compiler is ...
    (microsoft.public.vc.language)
  • bound template parameter as argument to friend member function declaration
    ... I'm attempting to use policies to create a generic memento (design ... My Memento template so far is pretty simple: ... My point in doing this is to force a compile-time check that Originator ... friend class Originator; //or this... ...
    (comp.lang.cpp)