- Template operators as member functions
#include<iostream>
#include<string>
using namespace std;
template <typename T> class Data{
private:
T value;
public:
Data(){};
Data(T v);
// Operator +
Data<T> operator+(const Data<T>& other);
// Operator +=
Data<T> operator+=(const Data<T>& other);
void display(void);
};
template <typename T> Data<T>::Data(T v)
{
this->value = v;
}
template <typename T> Data<T> Data<T>::operator+(const Data<T>& other)
{
Data<T> temp;
temp.value = this->value + other.value;
return temp;
}
template <typename T> Data<T> Data<T>::operator+=(const Data<T>& other)
{
this->value = this->value + other.value;
return *this;
}
template <typename T> void Data<T>::display(void)
{
cout << "value = " << this->value << endl;
}
int main()
{
Data<double> x(1.2);
Data<double> y(5.0);
Data<double> z(0.0);
x += y;
x.display();
return 0;
}
Summary 1
When overloading operators as member functions of a template class, its done similarly to defining template member functions.
- Template operators as friend functions
#include<iostream>
#include<string>
using namespace std;
template <typename T> class Data{
private:
T value;
public:
Data(){};
Data(T v);
template <typename U> friend Data<U> operator+(Data<U> &a, Data<U> &b);
/* Operator overload defined as a friend function inside the class.
friend Data<T> operator+(Data<T> &a, Data<T> &b)
{
Data<T> temp;
temp.value = a.value + b.value;
return temp;
}
*/
void display(void);
};
template <typename T> Data<T>::Data(T v)
{
this->value = v;
}
template <typename T> Data<T> operator+(Data<T> &a, Data<T> &b)
{
Data<T> temp;
temp.value = a.value + b.value;
return temp;
}
template <typename T> void Data<T>::display(void)
{
cout << "value = " << value << endl;
}
int main()
{
Data<double> x(1.2);
Data<double> y(5.0);
Data<double> z(0.0);
z = x + y;
z.display();
return 0;
}
Summary 2
When using operator overloads as friend functions, there are two cases to consider.
If the definition is inside the class, it can be written directly.
If the definition is outside the class, the declaration must include the template keyword, and the suffixes need to be adjusted accordingly, as long as they do not conflict with the class template suffix.