0

I am implementing assignment operator function for a template matrix class. It should take care of different datatype matrix assignments. eg Integer matrix is assigned to a double matrix. for that i have following declaration:

template<class U> MyMatrix<T>& operator= (const MyMatrix<U> &rhs) {...}

My problem is, if i implement the fuction within class declaration, it works. But if i implement it outside the class declaration like,

template<class T, class U> MyMatrix<T>& MyMatrix<T>::operator= (const MyMatrix<U> &rhs){...}

i get following error:

error: no declaration matches ‘MyMatrix<T>& MyMatrix<T>::operator=(const MyMatrix<U>&)’

What am i doing wrong?

3
  • 6
    An out-of-class definition would have to look like template<class T> template<class U> MyMatrix<T>& //etc. - you have a template within a template, not a template that takes 2 template parameters Commented Jun 6, 2023 at 10:07
  • @UnholySheep, can you please suggest resources where i can learn more about templates? Thanks Commented Jun 6, 2023 at 10:59
  • The only resource I can think of off the top of my head would be "Modern C++ Design" by Andrei Alexandrescu - but that is already a quite advanced text on templates. Otherwise I have mainly learnt by reading and working with code written by more experienced programmers Commented Jun 6, 2023 at 11:41

1 Answer 1

1

When providing out of class definition of a member template you've to provide the template parameter clause correspondimg to both the class template as well as the member template as shown below:

template<class T> // parameter clause for class template 
template<class U> // parameter clause for member template
MyMatrix<T>& MyMatrix<T>::operator= (const MyMatrix<U> &rhs)
{  // code here
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.