访问重载的模板函数

时间:2011-04-29 06:52:18

标签: c++ class templates operator-overloading typename

嘿伙计们, 我很困惑如何访问像这样的重载模板函数:

 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];}

我能够做到

 Matrix <double> test(number, number) 

例如,但我不知道如何使用模板化&gt;&gt;运营商(或&lt;&lt;或*或+ ..)任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

嗯,访问的唯一方法是这样的:

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

但它当然会破坏运算符重载的所有优点。所以这个运算符定义有问题。也许Matrix是一种模板类型,它应该是

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

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

答案 1 :(得分:0)

我假设您声明一个类型参数为Matrix的类模板T,并且您希望使用已定义的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>>视为函数)进行交互,如上面的代码所示,或者它可能想要与函数模板成为联系(所有实例化)或函数模板的特定实例化。

我写了很多关于不同选项和行为here的解释,我建议你阅读它。

相关问题