mardi 14 janvier 2020

Operator overloading for two different types of same templated class/structure?

I have a convenient class, Vector. It is really just a templated structure that holds 3 things. They can be floats, doubles, ints, etc.

IE:

template <typename T>
struct Vector 
{
 T x;
 T y;
 T z;
}

It has nice operator overloading, allowing me to add two vectors together, for example:

Vector operator+(const Vector& rhs) 
{
 return Vector(x + rhs.x, y + rhs.y, z + rhs.z);
}

However, what if I want to do this:

Vector<float> myFloatVec(0.2, 0.5, 0.95);
Vector<int> myIntVec(2, 5, 1);

Vector<float> result = myFloatVec + myIntVec; // cannot do this

And what if I later wanted to change types:

vector<int> result2 = static_cast<int>(result); // cannot do, this would be nice too

Is there any way to accomplish something like that easily in C++?

If I could somehow cast the integer vector into a float vector, then I could let the normal operator overloading take over. Sadly, I do not know of any way to overload how static_cast<> works on a type.

Aucun commentaire:

Enregistrer un commentaire