#include <iostream>
using namespace std;
template<class T>
class Array {
public: // should be private, big ignore that
int n;
T *arr;
public:
Array(int sz, T initValue) {
n = sz;
arr = new T[n];
for (int i=0; i<n; i++) arr[i] = initValue;
}
Array& operator = (const Array& b) {
if (this!=&b) {
delete[] arr;
n = b.n;
arr = new T[n];
for (int i=0;i<n;i++) arr[i] = b.arr[i];
}
return *this;
}
Array operator + (const Array& b) {
Array res(n, 0);
for (int i=0; i<n;i++) res.arr[i] = arr[i] + b.arr[i];
return res;
}
};
int main()
{
Array<double> a(10, 1); //Array<double> b(10, 2); // this works
Array<int> b(10, 2);
a = b; // error
for (int i=0; i<10; i++) cout << i << " " << a.arr[i] << "\n";
Array<double> c(10,0);
c = a + b; // error if b is <int>, runs if b is <double>
c = a - b;
c = a * b;
}
So I have a template class that can takes int, float, double,
...
Intuitively, Array<double> a; Array<int> b; a = b;
should be possible because element-wise, we can do a[i] = b[i]
. However, I have the conversion error because something is missing.
How can I make a = b;
possible? Thank you.
Edit: the point is not about making an Array. It can be a Matrix, 3dArray, etc. It's about assignment of a float template
and int template.
You can also replace int with float, and float with highPrecisionFloat, for example.
Edit 2: I forgot to mention, I not just only need operator =, but operator + (and - * /, etc) as well. If I user @churill answer, I need to do so for each operator. How can I make conversion from Array to Array implicit?