The implicit (implicit) type conversion of template functions involves the determination of template parameters (TypeName).
from type int or double, cannot be implicitly converted to the type of the template class (template class), because the template parameter type (typename) cannot be determined, the parameters of the constructor cannot be determined.
So you need to make a template function that has the same parameter type (typename) as the template class, and you need to be a friend of the template class.
The friend of the template class is instantiated with the parameters of the class, and the parameter types are instantiated, and custom functions are generated from a function template, that is, by implicit type conversions.
Because a custom function was generated, the external template class definition could not be found and could be achieved by:
1. Directly within the friend function, implementation code (inline);
2. Within the friend function, implement a template function in the external implementation of the template function.
The code is as follows:
* * * test.cpp * * Created on:2014.04.22 * author:spike//*eclipse CDT, gcc 4.8.1*/#inc
Lude <iostream> template<typename t> class Rational; Template<typename t> Const rational<t> domultiply (const rational<t>& LHS, const RATIONAL< ;
t>& RHS); Rational number//More Highlights: Http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/template<typename t> class Rational {/*friend const rational<t> operator* (const rational<t>& LHS, const rational< t>& RHS) {return rational<t> (Lhs.numerator () *rhs.numerator (), Lhs.denominator () *rh
S.denominator ()); }//Method 1*/friend Const rational<t> operator* (const rational<t>& LHS, const RATIONAL<T>
;& RHS) {return domultiply (LHS, RHS); }//Method 2 public:rational (const t& numerator = 0, const t& DenominatoR = 1): M_n (numerator), m_d (denominator) {} const T numerator () const {return m_n;};
Const T Denominator () const {return m_d;};
Const T Value () {return (m_n/m_d);}
Private:t M_n;
T M_d;
}; Template<typename t> Const rational<t> domultiply (const rational<t>& LHS, const Rationa l<t>& RHS) {return rational<t> (Lhs.numerator () *rhs.numerator (), Lhs.denominator () *rhs
. denominator ());
int main (void) {rational<double> Onefourth (1, 4);
rational<double> result;
result = Onefourth * 3.5;
result = 3.5 * Onefourth;
Std::cout << "result =" << result.value () << Std::endl;
return 0; }
Output:
result = 0.875
Author: csdn Blog spike_king