This article Senlie original, reproduced please retain this address:Http://blog.csdn.net/zhengsenlie
Experience: When we write a class template, and the "related to this template" function provides support for "implicit type conversion of all parameters". Define those functions as "friend functions inside the class template."
Demo Sample:
Template<typename t>class rational{public:rational (const t &numerator = 0, const t &denominator = 1)//Item 20 passes the passed by reference for the type of its own definition. Here T may be a built-in type or a self-defined type. Const T numerator () const; Item 28 avoids returning handles points to the inner component of the object. const denominator () const; };template<typename t>const rational<t> operator* (const rational<t> &LHS, const Rational<T > &RHS) {...} Rational<int> onehalf (1, 2); rational<int> result = Onehalf * 2; Error
Parse: operator* accepts two rational<t>, but it does not deduce what T is
The first number of operator* is declared as Rational <T>. The type of the first real participation (ONEHALF) passed to operator* is rational<int>, so t must be int
The second argument of operator* is declared as Rational <t>, while the type of second actual (2) passed to operator* is int. The compiler cannot deduce what T is
Correction 1: operator* is declared as a friend function of Rational<t> class. Can compile successfully, cannot link successfully
Template<typename>class rational{public:friend Const Rational operator* (const rational &LHS, const Rational & AMP;RHS);}; Template<typename t>const rational<t> operator* (const rational<t> &LHS, const Rational<T> &RHS) {...}
Parsing: Onehalf is Rational<int>, and the class rational<int> is detailed. The operator* that accept the rational<int> parameter are also detailed in the corresponding detail. Make it a function rather than a function template.
But the detailed function is declared in the Rational template. The operator* outside Rational template does not define it in detail.
Correction 2: Merging the operator* function body into a declarative type
Template<typename>class rational{public:friend Const Rational operator* (const rational &LHS, const Rational & AMP;RHS) {return Rational (Lhs.numerator () * Rhs.numerator (), Lhs.denominator () * rhs.denominator)}};
Effective C + + Item 46 When you need to cast your non-member function definition template