samedi 25 juillet 2020

C++ function that can take integer or float or double or any other castable to float

I am trying to implement a Vector3 struct in C++. I am overloading the "*" operator for handling multiplication with the scalar values. So it will work like this:

v1 = Vector3(1.0f, 1.0f, 1.0f);
v2 = 2*v1;
v3 = 2.4f*v1;
v4 = 2.4*v1;

All 3 operations will return a Vector3 instance. However, I don't want to implement 3 functions for this purpose.

    Vector3 operator * (int& const val) {
       float _val = static_cast<float> (val);
       return Vector3(x * _val, y * _val, z * _val);
    }

   Vector3 operator * (double& const val) {
           float _val = static_cast<float> (val);
           return Vector3(x * _val, y * _val, z * _val);
   }
   
   Vector3 operator * (float& const val) {
               return Vector3(x * val, y * val, z * val);
       }
    

Is there a better way of doing this with one function?

Aucun commentaire:

Enregistrer un commentaire