开发者

access overloaded template functions

hey guys, i'm confused as to how to access an overloaded template function like this one:

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

with a function such as:

 template <typename T>
 Matrix(T 开发者_运维问答r, T c) {rows=r; cols=c; elements=new T[r*c];}

i was able to do

 Matrix <double> test(number, number) 

for example, but i have no idea how to use a templated >> operator (or << or * or +..) any help would be appreciated. thanks!


I am assuming that you are declaring a class template Matrix that has a type argument T, and that you want to use the defined operator>> (you should make this more explicit in the question):

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

And then it is quite simple to use:

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

That is not the only option, it is just the most common one. That is in general a class template can befriend a single (non-templated) function (think operator<< and operator>> as functions) as in the code above, or it might want to befriend a function template (all instantiations) or a particular instantiation of a function template.

I wrote a long explanation of the different options and behaviors here, and I recommend you to read it.


Well, the only way to access is something like this:

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

but it of course defeats all the advantages of operator overloading. So there is something wrong with this operator definition. Maybe Matrix is a template type and it should be

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

I see no use of template parameter in your operator definition, so something is wrong with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜