Why do you need
templates for such a task?
Could you please show us your 'not working code'?
Here an example of global (without class) operator overloading:
How to overload opAssign operator globally in C++ - Stack Overflow[
^].
[update]
I give you an example
#include <iostream>
using namespace std;
template <typename complex_t>
struct complex
{
complex_t real, imag;
complex( complex_t r, complex_t i):real(r), imag(i){}
complex():real(complex_t()), imag(complex_t()){}
};
template <typename complex_t >
complex<complex_t> operator + ( const complex<complex_t> & a, const complex<complex_t> & b)
{
complex<complex_t> c;
c.real = a.real + b.real;
c.imag = a.imag + b.imag;
return(c);
}
int main()
{
complex <double> c1(1,-2);
complex <double> c2(2.3,19);
complex <double> c3 = c1 + c2;
cout << "c3.real = " << c3.real << ", c3.imag = " << c3.imag << endl;
}
Note, since
C++11
, you might write
template <typename complex_t>
struct complex
{
complex_t real{}, imag{};
complex( complex_t r, complex_t i):real(r), imag(i){}
complex(){}
};
instead.
[/update]