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!
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;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments