My question might sound weird because of how precise the problem is.
So, for the context, i have created a multidimensional array class :
template <typename TYPE>
requires std::integral<TYPE> || std::floating_point<TYPE>
class MultiArray {
int mDim = 0;
std::vector<int> mShape = {};
std::vector<TYPE> mArray = {};
[METHODS]
}
(A multiArray object need a dimension, a shape that is the same size of the dimension and the "mArray" is the array that have all the elements of the MultiArray which type is dependent of the template)
I'm trying to do an "=" operator overloading but my MultiArray objects can do maths operations (like numpy in python) so their type can change. I want to be able to do things like this :
MultiArray<int> M(2,5); //Creating a 5x5 matrix of zeroes
M = M 2.12; //I want M to be 5x5 matrix of 2.12
BUT my M is an "int" MultiArray and, because i'm adding a float, "M 2.12" return a "double" MultiArray so I have to convert my M into a MultiArray "double".
With the operator overloading, I tried :
template <typename TYPE>
void operator=(MultiArray<TYPE> MultiArr) {
// defining the return type
using TYP_RE = std::conditional_t<std::is_floating_point<TYPE>::value, double, int>;
// we allocate the dimension and the shape
this->mDim = MultiArr.getDim();
this->mShape = MultiArr.getShape();
// we calculate the size of the 1-D mArray
int taille = 1;
for (int i = 0 ; i < mDim ; i ) {
taille *= this->mShape[i];
}
// we create a new array that will contain the new values
std::vector<TYP_RE> Array;
std::vector<TYPE>& Arr = MultiArr.getArray();
for (int i = 0 ; i < taille ; i ) {
Array.push_back(static_cast<TYP_RE>(Arr[i]));
}
// We allocate this new array into the old array
this->mArray.clear();
this->mArray.swap(Array);
}
The problem is with the last command. I can't swap a "double" vector with an "int" vector and I'm stuck here.
Have a nice day !
CodePudding user response:
this->mArray.clear();
this->mArray.swap(Array);
should be
this->mArray.assign(Array.begin(), Array.end());
we create a new array that will contain the new values
- this intermediate Array
looks redundant.
CodePudding user response:
Maybe you are looking for something like this?
template <class T, class U>
auto operator (const MultiArray<T>& a, U b>)
-> MultiArray<decltype<declval<T>() b>>
{
MultiArray<decltype<declval<T>() b>> rslt;
// do the math;
return rslt;
}
And then
MultiArray<int> M(2,5); //Creating a 5x5 matrix of zeroes
auto N = M 2.12; //I want M to be 5x5 matrix of 2.12