Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Taming Friends for Use in Templates-4 : Page 4


advertisement
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



Danny Kalev is a certified system analyst and software engineer specializing in C++. He was a member of the C++ standards committee between 1997 and 2000 and has since been involved informally in the C++0x standardization process. He is the author of "The ANSI/ISO Professional C++ Programmer's Handbook" and "The Informit C++ Reference Guide: Techniques, Insight, and Practical Advice on C++."
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap