0

I am trying to overload += operator for my template Polynom class in a way so I would be able to use both Polynoms and constants as argument.

I wrote a constructor and following operator inside my class:

Polynom(const T& num = 0) {
  coefs.push_back(num);
}
friend Polynom& operator += (Polynom& lhs, const Polynom& rhs) {
  ...
}

And it works fine, I am able to use: poly += 1;. When compiler runs into something likes that what does it do? It sees that there is no += operator that uses these arguments:

(Polynom<int>& lhs, const int)

But there is one for:

(Polynom<int>& lhs, const Polynom& rhs)

So, it tries to convert const int to const Polynom&? And it uses constructor for that, right? But then why doesn't this declaration work when adding a constant:

Polynom& operator += (Polynom& rhs) {
  ...
}

Compiler says "no match for operator +=".

grozhd
  • 481
  • 1
  • 5
  • 13

2 Answers2

3

When passing an int to a function taking a const Polynom&, the compiler is able to construct a temporary Polynom object from the int that is then bound to the const Polynom& parameter. However this doesn't happen with the Polynom& parameter because temporaries cannot be bound to non const references.

David Brown
  • 13,336
  • 4
  • 38
  • 55
  • I found this: http://stackoverflow.com/questions/1565600. This explains my problem, right? It is just a rule that I can't bind a non-const ref to temp object. – grozhd Nov 15 '12 at 21:15
  • @grozhd yes it's just one of the rules in the standard. Those answers explain it in much more detail – David Brown Nov 15 '12 at 21:29
0

You need to show us the template code or your smallest compilable code that demonstrates the issue.

Try creating a method that accepts an integer parameter:

friend Polynom& operator+=(const Polynom& lhs, int constant);

I'm confused about your notation Polynom<int> which indicates your Polynom class is a template.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154