0

What is the difference between these two codes I just don't understand what the problem is.

Version 1 which works perfectly:

template <class T>
T max (T& a, T& b)
{
    return a < b ? b : a;
}

int main()
{
    auto i = 2;
    auto j = 3;
    cout << "max(i, j): " << max(i, j) << endl;
    return 0;
}

Version 2 which does not work:

template <class T>
T max (T& a, T& b)
{
    return a < b ? b : a;
}

int main()
{

    cout << "max(i, j): " << max(44, 33) << endl;
    return 0;
}

So my question is why does the second version of the same code not work. Can someone tell me what the problem is with it. In the second version the max(44, 33) are underlined in red. The error message reads: Error C2664: 'T max <int>(T &, T &)': cannot convert argument 1 from 'int' to 'int&'(15) I really don't understand this error and I really want someone to explain why this is happening and how can I fix this. Also when you hover under the max is reads: no instance of function template max matches the argument list argument types are: (int, int).

Jakub Gawel
  • 63
  • 1
  • 6
  • 1
    Related: https://stackoverflow.com/questions/1565600/how-come-a-non-const-reference-cannot-bind-to-a-temporary-object – Rakete1111 Sep 04 '17 at 13:56
  • I should add that I am also a beginner to this. So I did not understand anything in that related post :) – Jakub Gawel Sep 04 '17 at 13:57
  • The title of the related post answers your question. In that case you should look into the parts of the title which you don't understand. :) – DeiDei Sep 04 '17 at 14:01
  • @Jacub - When you pass the parameter by reference, the function can change the value of the argument. If the function contains `++a;` that would change `i` from 2 to 3. Should it also be able to change 44 to 45? No! So a long time ago it was decided not to allow passing 44 in a way so that a function might change it. – Bo Persson Sep 04 '17 at 14:25
  • Change the template to `T max(const T& a, const T& b)`. – Pete Becker Sep 04 '17 at 15:12

0 Answers0