You can overload the + operator using a member function or a non-member function.
When the operator is overloaded using a member function, the LHS of the operator is the object on which the function will be called and RHS of the operator is the argument to the function. Hence, the only argument to the member function will be the RHS.
When the operator is overloaded using a non-member function, the LHS of the operator is the first argument of the to the function and RHS of the operator is the second argument to the function.
Member function
template<typename T>
class Matrix
{
Matrix operator+(const Matrix& rhs) const {
...
}
};
If you want to implement it outside the class definition, you can use:
template<typename T>
Matrix<T> Matrix<T>::operator+(const Matrix& rhs) const {
...
}
Non-member function
template<typename T>
class Matrix
{
Matrix operator+(const Matrix& lhs, const Matrix& rhs) {
...
}
};
If you want to implement it outside the class definition, you need to add some forward declaration code:
// Forward declare the class template
template <typename T> class Matrix;
// Declare the function
template <typename T> Matrix<T> operator+(const Matrix<T>& lhs, const Matrix<T>& rhs);
// Declare the friend in the class definition
template <typename T>
class Matrix
{
friend Matrix operator+<T>(const Matrix& lhs, const Matrix& rhs);
// ^^^^
// This makes operator+<int> a friend of Matrix<int>, not a friend
// of Matrix<double>
};
and then implement the function
template <typename T> Matrix<T> operator+(const Matrix<T>& lhs, const Matrix<T>& rhs)
{
...
}
With this setup, oprator+<int>
is a friend of Matrix<int>
only, not a friend
of Matrix<double>
.
If you use
template <typename U>
friend
Matrix<U> operator+(const Matrix<U>& a, const Matrix<U>& b);
then, all instantiations of operator+
are friends of all instantiations of Matrix
, which you don't need.
Update
Sample working code:
#include <iostream>
// Forward declare the class template
template<typename T> class Matrix;
// Declare the function
template <typename T> Matrix<T> operator+(const Matrix<T>& lhs, const Matrix<T>& rhs);
// Declare the friend in the class definition
template <typename T>
class Matrix
{
friend Matrix operator+<T>(const Matrix& lhs, const Matrix& rhs);
// ^^^^
// This makes operator+<int> a friend of Matrix<int>, not a friend
// of Matrix<double>
};
template <typename T> Matrix<T> operator+(const Matrix<T>& lhs, const Matrix<T>& rhs)
{
return Matrix<T>{};
}
int main()
{
Matrix<int> a;
Matrix<int> b;
Matrix<int> c = a + b;
}