访问重载的模板函数

access overloaded template functions

本文关键字:函数 重载 访问      更新时间:2023-10-16

大家好,我对如何访问像这样的重载模板函数感到困惑:

 template <typename T>
 friend istream& operator>> (istream& in, Matrix& right)
 {
      for(int i=0; i<right.rows*right.cols; i++)
        cin >> right.elements[i];
 }

带有如下函数:

 template <typename T>
 Matrix(T r, T c) {rows=r; cols=c; elements=new T[r*c];}

i was able do

 Matrix <double> test(number, number) 
例如

,但我不知道如何使用模板化的>>操作符(或<<)或*或+…)任何帮助将不胜感激。谢谢!

我假设您正在声明一个具有类型参数T的类模板Matrix,并且您想使用已定义的operator>>(您应该在问题中更明确地说明这一点):

template <typename T>
class Matrix {
   int rows, cols;
   T* elements;
public:
   Matrix( int c, int r );        // Do you really want the number of 
                                  // rows/columns to be of type `T`??
   // Note: removed template, you only want to befriend (and define)
   // a single operator<< that takes a Matrix<T> (the <T> is optional
   // inside the class braces
   friend std::istream& operator>>( std::istream& i, Matrix& m )
   {
       // m.rows, m.cols and m.elements is accessible here.
       return i;
   }
};

使用起来很简单:

Matrix<double> m( 1, 2 );
std::cin >> m; 

这不是唯一的选择,它只是最常见的一个。一般来说,类模板可以像上面的代码那样与单个(非模板化的)函数(将operator<<operator>>看作函数)为友,或者它可能想与函数模板(所有实例化)或函数模板的特定实例化为友。

我在这里写了一篇很长的关于不同选项和行为的解释,我建议你读一读。

唯一的访问方式是这样的:

operator>> <YourType> (istream, param);

,但它显然破坏了操作符重载的所有优点。所以这个算子的定义有问题。也许Matrix是模板类型,它应该是

template <typename T>
operator>>(istream & in, Matrix<T> & right);

我在你的操作符定义中没有看到模板参数的使用,所以它有问题。