Can you explicitly use a constructor overload?

124 Views Asked by At

If I have 2 constructor overloads

calculations(double vector, double angle);
calculations(double horizontalVector, double verticalVector);

How can I ensure the compiler specifically uses one of the overloads that I choose (as each of them do different things behind the scenes)?

3

There are 3 best solutions below

0
On

If you want to have overloads, the types needs to be different. One way to do this is the so called whole value idiom.

Make a struct for each parameters: a vector (watching out for potential name clashes), angle and so on.

The you will have two different constructors.

0
On

To provide different functions with same parameters you can use tag dispatching, where you provide unused parameter to do overloading.

struct Calculations {
  struct UseTwoVectors {};
  Calculations(double vector, double angle);
  Calculations(double horizontalVector, double verticalVector, const UseTwoVectors&);
};
int main() {
    Calculations c(1, 2);
    Calculations d(1, 2, Calculations::UseTwoVectors());
}

Overall I do not know what these arguments represent - I suspect there is something wrong with abstraction in your code. You could take a different approach and make a class from your parameters.

struct VectorAngle {
    double vector, angle;
};
struct TwoVectors {
    double horizontalVector, verticalVector;
};
struct Calculations {
  Calculations(const VectorAngle& v);
  Calculations(const TwoVectors& v);
};
int main() {
    Calculations c(VectorAngle{1, 2});
    Calculations d(TwoVectors{1, 2});
};
1
On

Assuming that your parameters are actually polar and cartesian coordinates rather than vectors,

calculations(double length, double angle);
calculations(double x_coordinate, double y_coordinate);

you can abstract those into types,

struct Polar { double length, angle; };
struct Cartesian {double x, y; };

and overload

calculations(const Polar& p);
calculations(const Cartesian& c);

and then

calculations c1(Polar{1,1});
calculations c2(Cartesian{1,1});