函数模板不接收参数的隐式转换

  1. template<typename T>
  2. class Rational {
  3. public:
  4. Rational(const T& a = 0,const T& b = 1) : a(a),b(b) {}
  5. const T getA() const;
  6. const T getB() const;
  7. };
  8. template<typename T>
  9. const Rational<T> operator*(const Rational<T>& a,const Rational<T>& b) {
  10. return Rational<T>(a.getA() * b.getA(),a.getB() * b.getB());
  11. }
  12. int main() {
  13. Rational<int> r(1,2);
  14. Rational<int> res = r * 3;
  15. return 0;
  16. }

image.png
原因:在调用一个函数首先需要知道函数存在,函数模板首先要推导出参数类型,才可以将函数模板具现化出来,但是在模板函数实参推导的时候,不会考虑构造函数的隐式类型转换的

在类模板里声明友元函数

  1. template<typename T>
  2. class Rational {
  3. public:
  4. Rational(const T& a = 0,const T& b = 1) : a(a),b(b) {}
  5. friend const Rational<T> operator*(const Rational<T>& a,const Rational<T>& b);
  6. ……
  7. };
  8. template<typename T>
  9. const Rational<T> operator*(const Rational<T>& a,const Rational<T>& b) {
  10. return Rational<T>(a.getA() * b.getA(),a.getB() * b.getB());
  11. }

image.png
模板实参推导只存在于函数模板,所以r被声明出来之后,类模板class Rational被具现化出来,在这个过程中,friend函数接受了int参数之后也被声明了出来,普通的函数是可以进行隐式转换的
虽然编译没有问题,但是出现了连接错误
在类模板里,可以用模板名称替代模板名称 + 参数类型

  1. friend const Rational operator*(const Rational& a,const Rational& b);

在类模板里定义友元函数

  1. template<typename T>
  2. class Rational {
  3. public:
  4. Rational(const T& a = 0,const T& b = 1) : a(a),b(b) {}
  5. friend const Rational operator*(const Rational& a,const Rational& b) {
  6. return Rational<T>(a.getA() * b.getA(),a.getB() * b.getB());
  7. }
  8. ……
  9. };

让友元函数调用类外部的函数

image.png
image.png
operator*不做任何事情,只去调用class外部的模板函数