【问题标题】:access overloaded template functions访问重载的模板函数
【发布时间】:2011-04-29 06:52:18
【问题描述】:

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

 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) 

例如,但我不知道如何使用模板化的 >> 运算符(或

【问题讨论】:

  • 您需要添加更多上下文,特别是类模板声明,包括成员属性和现有代码它实际上在哪里在类模板中(或在它之外) )。

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


【解决方案1】:

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

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&lt;&lt;operator&gt;&gt; 作为函数)成为朋友,或者它可能想要与函数模板(所有实例化)或一个函数模板的特定实例化。

我对@9​​87654321@ 的不同选项和行为进行了长篇解释,建议您阅读。

【讨论】:

  • 抱歉,这不起作用。它声称 right.cols, right.rows...没有模板类型名 T 行是无法访问的
  • @pauliwago:你真的应该添加封闭类模板声明和上下文的成员声明。否则,您要求在关灯的房间中搜索物体。您是否在 Matrix 类模板中定义运算符?
【解决方案2】:

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

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

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

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

我发现您的操作符定义中没有使用模板参数,所以它有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-04
    • 1970-01-01
    • 2015-02-27
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多