Aren't Friends Electric?
We're reaching the last twist in this thick plot. Suppose you want to define an overloaded
== function template that accepts different types of arguments:
// asymmetric, used in Vector<int> == Vector<double> etc.
template <typename T, typename T2>
bool operator== (const Vector<T> &a,
const Vector<T2> &b);
Such an asymmetric overloaded operator probably reminds you the
asymmetric assignment operator discussed here recently. Here again you have two distinct template parameters,
T and
T2. How do you declare such an asymmetric overloaded operator as a friend? Here's the answer:
template <typename T> class Vector {
T val;
public:
explicit Vector(T v = 0): val(0){}
~Vector(){}
//asymmetric operator ==
template <typename T2>
friend bool operator==(const Vector <T> &a,
const Vector <T2> &b);
};
//definition of asymmetric operator==
template <typename T, typename T2>
bool operator== (const Vector<T> &a,
const Vector<T2> &b)
{
return a.val == b.val;
}
Vector<int> vi, vi2;
Vector<double> vd;
bool equal =
vi == vi2; // OK
equal =
vi == vd;// OK