0

I have created a custom variable length vector class Vec with the following overloaded operators:

float& operator[](int i);
Vec& operator+=(Vec& rhs);
Vec operator+(Vec& rhs);
Vec& operator-=(Vec& rhs);
Vec operator-(Vec& rhs);
Vec& operator*=(float rhs);
Vec operator*(float rhs);
Vec& operator/=(float rhs);
Vec operator/(float rhs);

These overloads work fine individually and I get the correct results, but when I try to chain them I get compilation errors with template argument deduction/substitution failed. Does anyone have any idea why?

This works:

Vec multiplier = d * time;
Vec collision = e + multiplier;

This fails: Vec collision = e + (d * time);

e and d are of type Vec, time is of type float

Jeremy Robertson
  • 115
  • 2
  • 11
  • 4
    You want a few consts in there. –  Nov 13 '18 at 20:40
  • 3
    Not enugh code posted. Better post a [mcve](https://stackoverflow.com/help/mcve) – Ripi2 Nov 13 '18 at 20:42
  • 1
    https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading . You should not use `Vec& rhs` on the right (either use `Vec` or `Vec const&`), and it would be better if the `+ - * /` were non-member functions – M.M Nov 13 '18 at 21:47

1 Answers1

0

The problem is that you've declared your functions as taking Vec &rhs arguments instead of const Vec &rhs. The lack of a const means that you can only pass a reference to a real (named) object; you can't pass a reference to an unnamed temporary object.

When you "chain" operations, the result of the inner operation will be an unnamed temporary, which then can't be passed to the outer operation, so you get overload resolution failures (which manifest as template substitution failures, as your class is apparently actually a template)

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226