Reputation: 1017
I am just starting with c++ and I don't have a lot of knowledge about templates, I made a template function and I am recieving this error in Visual Studio:
//No instance of function template "max" matches the argument list argument types are (int, int) //C2664'T max(T &,T &)': cannot convert argument 1 from 'int' to 'int &'
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class T>
T max(T& t1, T& t2)
{
return t1 < t2 ? t2 : t1;
}
int main()
{
cout << "The Max of 34 and 55 is " << max(34, 55) << endl;
}
The copiling error is found in the max of the cout
Thank you!
Upvotes: 3
Views: 5868
Reputation: 9989
A non-const
reference parameter must be backed by an actual variable (loosely speaking). So this would work:
template <class T>
T max(T& t1, T& t2)
{
return t1 < t2 ? t2 : t1;
}
int main()
{
int i = 34, j = 55;
cout << "The Max of 34 and 55 is " << max(i, j) << endl;
}
However, a const
reference parameter does not have this requirement. This is probably what you want:
template <class T>
T max(const T& t1, const T& t2)
{
return t1 < t2 ? t2 : t1;
}
int main()
{
cout << "The Max of 34 and 55 is " << max(34, 55) << endl;
}
Upvotes: 6
Reputation: 108
Your function is expecting two l-value references, though, what you're passing are two r-values.
Either pass two variables or change the function signature to accept r-value references.
Upvotes: 3